post  Hex bytes to integer

Jo3Bingham (5)   Link to this post
I have a byte array and I need to convert the first two bytes to an integer as though they're one byte, but they have to be read backwards.

ie. The first byte is A1 and the second byte is B2. I need to convert them as B2A1.

Thanks ahead of time. :)
jsmith (3799)   Link to this post
If sizeof( unsigned short ) == 2 and your platform is little endian (Intel), then
just

1
2
unsigned char byte_array[ 2 ]; // ...
unsigned short val = *(unsigned short*)byte_array;

helios (6064)   Link to this post
Regardless of platform, you can do unsigned long a=array[0]|(array[1]<<8); and it will always work (unless sizeof(unsigned long)<2).
Last edited on
Jo3Bingham (5)   Link to this post
Thanks helios, you too jsmith.

This topic is archived - New replies not allowed.