Pikachu
Pikachu

Reputation: 31

Swap two nibbles in a byte

I am trying to swap two nibbles in a byte on my own. The solution on the Internet seem obvious which is

( (x & 0x0F)<<4 | (x & 0xF0)>>4 )

I know how the above solution works. I tried on my own which looks something like this

(((0x0F<<4)&(n)) | (0x0F & (n>>4)))

In the first operation : I am trying to shift 1111 4 places to the left and then & with n to get the first four bits.

In the second operation: I am trying to shift n 4 place to the right and then & with 1111 to get the last four bits.

And then OR to give the final answer.

What is wrong with my approach?

Upvotes: 2

Views: 1523

Answers (1)

Peter de Rivaz
Peter de Rivaz

Reputation: 33509

Consider a number in binary:

abcdwxyz

When using ( (x & 0x0F)<<4 | (x & 0xF0)>>4 ):

(x & 0x0F)<<4 gives wxyz0000

(x & 0xF0)>>4 gives 0000abcd

so the final answer is wxyzabcd.

When using (((0x0F<<4)&(n)) | (0x0F & (n>>4))) instead, (0x0F<<4) is the same as 0xF0, so:

(0xF0 & (n)) gives abcd0000

(0x0F & (n>>4)) gives 0000abcd

so the final answer is abcdabcd.

Instead you could try:

((0xF0 & (n<<4)) | (0x0F & (n>>4)))

Upvotes: 7

Related Questions