In C language, how do I perform bit manipulation on int to swap adjacent nibbles?
The input given to me is 0xDEAD and the expected output is 0xEDDA.
In C language, how do I perform bit manipulation on int to swap adjacent nibbles?
The input given to me is 0xDEAD and the expected output is 0xEDDA.
Copyright © 2021 Jogjafile Inc.
Let's call each 4-bit group a nibble. Index the nibbles from right to left starting from 1. In the example
0xDEAD, the nibble with index 1 isD, index 2 isA, index 3 isE, and index 4 isD.Let's track where each nibble goes. The nibbles with odd indices go to the corresponding even indices, which is a nibble to the left. The nibbles with even indices go a nibble to the right.
Then we can pick each category of nibbles. The nibbles with odd indices can be picked with the bitmask
0x0f0f0f0f, and the even ones can be picked with0xf0f0f0f0. Here we bitwise-and the input with the bitmask to pick the bits.Then we can shift them by 4 bits (i.e. a nibble) to the left and to the right respectively and then bitwise-or them to get the answer.
The code is as follows: