I found some code in a built in library that I have and need to extend.
But it appears to be broken:
#define BSWAP16(__x) ((((__x) >> 8) | ((__x) << 8)))
Does not function the same as:
__builtin_bswap16()
This program proves it.
#include <stdio.h>
#define BSWAP16(__x) ((((__x) >> 8) | ((__x) << 8)))
int main(int argc, char* argv[])
{
unsigned short a = (unsigned short)BSWAP16(0xff00);
unsigned short b = __builtin_bswap16(0xff00);
short c = (short)BSWAP16(-8);
short d = __builtin_bswap16(-8);
printf("a=%04x, b=%04x, c=%04x, d=%04x\n", a,b,c,d);
return 0;
}
Output:
a=00ff, b=00ff, c=ffffffff, d=fffff8ff
I'm not wanting answers telling me I should use endian.h or __builtin_bswap16. On the target platform used by this in-house library on this platform/compiler configuration, I'm triggering this default code that is defaulting to using the above macro.
So my question is. Why doesn't it work for negative numbers?
If I represent -8 as a short value of 0xfff8 it works.
So I'm guessing it has something to do with internal conversion to int.
How do I fix this macro to work properly?