types - Shift operator in C prepends ones instead of zeros -


here code:

#define u8 char #define u32 unsigned int  typedef struct {     //decoded instruction fields     u8 cond; // condition (f.ex. 1110 true)     u8 instruction_code; // constant since use branch     u32 offset; // offset current pc } dcdinst;  u8 mem[1024];  mem[0x0] = 0b11101010;  u8* instruction_addr = &mem[pc];  if (instruction_addr == null) {     return false; }  unsigned int first_part = instruction_addr[0];  // here code presents problem: // try upper part of first byte inst.cond = first_part >> 4; 

first_part following byte: 11101010. inst.cond becomes 11111110, need 00001110.

so, actual problem want first 4 bits of instruction starts @ address instruction_addr. tried using right shift operator >> problem instead of prepending 0s left of byte, prepends 1s.

i found on stackoverflow first had cast value unsigned one, , that's did using variable first_part, still have same problem. don't understand why shift seems "see" variable negative 1 while type "unsigned".

does have idea?

your u8 type using char without specifying signedness, means has undefined signedness. it's compiler using signed char default. thus, you're subject sign-extension during operations , during promotion.

change:

#define u8 char #define u32 unsigned int 

to:

typedef unsigned char u8; typedef unsigned int u32; 

(or use stdint.h types properly), , storage should unsigned.

using typedefs means compiler involved aliasing, it's not preprocessor text replacement, eliminating class of subtle errors.


Comments