Itay Avraham
Itay Avraham

Reputation: 19

C Macro - variables types, how does it work?

#define CHANGE_OP_MODE      0

#define SetID(ID)   (((unsigned char)ID << 8) | ((unsigned char)(CHANGE_OP_MODE)))

short x = 0;
char y = 1;

x = SetID(y);

Moving 8 bits causes the ID to be 0, so why is X == 1?

Upvotes: 0

Views: 62

Answers (2)

Alex44
Alex44

Reputation: 3855

Your shifting becomes always zero. A char consits of 8 bit. So you push the value of ID with <<8 outside of this field. The bits right of ID, whish becomes free, will fill up with zeros.

Upvotes: 0

Eugene Sh.
Eugene Sh.

Reputation: 18299

The bitshift operator is implicitly casting it's operands to int, regardless your explicit cast to unsigned char. So shifting left an int value of 1 by 8 will yield value of 2^8=256. Which is actually the result that I am getting.

Upvotes: 1

Related Questions