1

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?

3
  • 2
    On almost all platforms, int is a 32 bit type. You initialize num to 0x00008000, and all bits are significant. Commented Aug 29, 2021 at 19:19
  • Using just bit operations is valid for unsigned int. For signed type the bit representation is different. Commented Aug 29, 2021 at 19:29
  • Use (unsigned) short int, or better, (u)int16_t, then you will get the result you want. Commented Aug 29, 2021 at 20:27

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks - so is this the general way always to swap 16 bits number?
No, general way is to use htons() and ntohs() functions
Thanks - I meant using bit pattern - in many places I see code like - (num << 8 ) | (num >> 8) ?
@Programmer That works with uint16_t. If you use a type wirh more than 16 bits, you need a bitwise AND to remove any set bits above the 16th bit

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.