long int FinalValue;
char a,b,c,d;
a=0x1;
b=0x2;
c=0x3;
d=0x4;
FinalValue |= (long)a;
FinalValue <<= 0x8;
FinalValue |= (long)b;
FinalValue <<= 0x8;
FinalValue |= (long)c;
FinalValue <<= 0x8;
FinalValue |= (long)d;
Printf("%d, %d, %d, %d", a,b,c,d);
Printf("FinalValue = %ld"FinalValue);
Output obtained:
1 2 3 4
FinalValue = 0x05020304
Expected Output:
1 2 3 4
FinalValue = 0x01020304
When the above code is executed with different inputs (for a,b,c,d), the output obtained in MSB of final value is: 0x(a|d)bcd (in the above example 0x1 or with 0x4, to obtaine 0x5)
Why is the MSB byte is getting ORed with LSB byte?
First initialize
FinalValueto0, uninitialized local (automatic) variables contain garbage.change
Printf("FinalValue = %ld"FinalValue);toprintf("FinalValue = %ld", FinalValue);, add the comma.What is
Printf? You probably meantprintf.You want output in hex ? Use
%lx.printf("FinalValue = %lx", FinalValue);Make
FinalValueunsigned and then shift. Shifting of the signed bit of a signed number is implementation dependent.UPDATE: added point 5