hemanth
hemanth

Reputation: 352

Error in conversion of char to long

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?

Upvotes: 1

Views: 125

Answers (1)

phoxis
phoxis

Reputation: 61940

  1. First initialize FinalValue to 0, uninitialized local (automatic) variables contain garbage.

  2. change Printf("FinalValue = %ld"FinalValue); to printf("FinalValue = %ld", FinalValue); , add the comma.

  3. What is Printf ? You probably meant printf .

  4. You want output in hex ? Use %lx . printf("FinalValue = %lx", FinalValue);

  5. Make FinalValue unsigned and then shift. Shifting of the signed bit of a signed number is implementation dependent.

UPDATE: added point 5

Upvotes: 5

Related Questions