I have a very small code where I am trying to convert a 16 bit number from little endian to big endian format.
The value of number is 0x8000 and after conversion I am expecting it to be as 0x0080 - but I am getting some different value as mentioned below:
#include <iostream>
int main()
{
int num = 0x8000;
int swap = (num>>8) | (num<<8);
std::cout << swap << std::endl;
return 0;
}
The program outputs 8388736 as value which in hex is 0x800080 - I am not sure what wrong am I doing?
CodePudding user response:
If you do 0x8000 << 8 you'll get 0x800000. If you | that with 0x80 you get the answer you now get. You need to filter away the upper part:
int swap = (num>>8) | (0xFF00 & (num<<8));
Suggestion: Use fixed width types, like uint8_t, uint16_t, uint32_t and uint64_t.
