0

Given these bytes (hexadecimal representation):

0F  
1A  
2C  

how can I get:

F0  
A1  
C2  

?

Dennis
  • 37,026
  • 10
  • 82
  • 150

2 Answers2

4

Use bitwise operators.

((x & 0x0f) << 4) | ((x & 0xf0) >> 4)
Josh Kelley
  • 56,064
  • 19
  • 146
  • 246
2

You can do it like this:

((x & 0x0f) << 4 ) | ((( x & 0xf0) >> 4) & 0xf )

This looks a lot like Josh Kelley's answer, but Josh's answer is wrong. Here's why:

#include <stdio.h>

int main( int argc, char *argv[] )
{
  signed char x = 0x80;
  x >>= 4;
  printf( "%x\n", x ); 
}

Gives output:

0xfffffff8

Because the >> operator preserves the sign bit of the shifted operand. I.e., a 1 in the most significant bit will be propagated leftward to preserve the sign of the value.

Heath Hunnicutt
  • 18,667
  • 3
  • 39
  • 62
  • Are you sure? My answer worked when I tested it. `(x & 0xf0)` should cause `x` to get promoted to `int` or `unsigned`, so its MSB will be 0, so it won't get sign-extended, right? – Josh Kelley Jun 23 '16 at 18:41
  • The sign extension in your example is actually being done at the `printf` call. `signed char x = 0x80; printf("%x\n", x);` gives `ffffff80`. – Josh Kelley Jun 23 '16 at 18:41
  • So, for `unsigned char` your answer and Josh's answer are equal? – Dennis Jun 23 '16 at 19:02