[C] Swapping 4-bits By Mapping

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
Here's an idea I came up with and wrote some code for... Say we have an integer 0x123456. If you were to map each digit out with any other digit from 0-F by a pre-defined mapping, how could you swap each 4-bit value out with it's new value to generate a completely new number?

Take this mapping for instance:
Code:
[NO-PARSE]Swaps:
1-5
2-6
3-4[/NO-PARSE]

Now each value of 1 would be swapped out with 5, 2 and 6, 3 and 4, 4 and 3, 6 and 2, 5 and 1.

Effectively 0x123456 becomes 0x564312.

Here's my pseudo-code which achieves this:
Code:
[NO-PARSE]#include <stdio.h>

int main()
{
  int bit_map[] = {
    0, 4, 6, 5, 1, 3, 2, 7, 8, 9, // swap 1-6, keep 0 & 7-9 unchanged
    0xA, 0xB, 0xC, 0xD, 0xE, 0xF  // keep A-F unchanged
  };

  int x = 0x2461355;
  unsigned char *ptr = (unsigned char*)&x;

  for (size_t i = 0; i < sizeof(x); ++i)
  {
    *(ptr + i) = (((*(ptr + i) >> 4) & 0xF) << 4) | bit_map[*(ptr + i) & 0xF];
    *(ptr + i) = (bit_map[(*(ptr + i) >> 4) & 0xF] << 4) | (*(ptr + i) & 0xF);
  }
  printf("0x%.6X\n", x);
}[/NO-PARSE]

Result:
Code:
[NO-PARSE]0x6124533[/NO-PARSE]

Your own map is defined within the bit_map local array. I love bitwise operations. The cool part about this is that in order to get the original value back, you don't need to change any of the bitwise operations that I've written.

I also thought about using a cyclical algorithm and XOR'ing each 4-bits with a pre-defined key for the same reason of being easy to reverse.

:thumbsup2:
 
Last edited:

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top