views:

74

answers:

2

I have an 8 digit hexadecimal number of which I need certain digits to be either 0 or f. Given the specific place of the digits is there a quick way to generate the hex number with those places "flipped" to f. For example:

flip_digits(1) = 0x000000f
flip_digits(1,2,4) = 0x0000f0ff 
flip_digits(1,7,8) = 0xff00000f 

I'm doing this on an embedded device so I can't call any math libraries, I suspect it can be done with just bit shifts but I can't quite figure out the method. Any sort of solution (Python, C, Pseudocode) will work. Thanks in advance.

+4  A: 

You can define eight named variables, each with a given nibble set all bits on:

unsigned n0 = 0x0000000f;
unsigned n1 = 0x000000f0;
unsigned n2 = 0x00000f00;
unsigned n3 = 0x0000f000;
unsigned n4 = 0x000f0000;
unsigned n5 = 0x00f00000;
unsigned n6 = 0x0f000000;
unsigned n7 = 0xf0000000;

Then you can use the bitwise-or to combine them:

unsigned nibble_0 = n0;
unsigned nibbles_013 = n0 | n1 | n3;
unsigned nibbles_067 = n0 | n6 | n7;

If you want to combine them at runtime, it would likely be simplest to store the constants in an array so they can be accessed more easily (e.g., n[0] | n[6] | n[7]).

James McNellis
+4  A: 
result = 0
for i in inputs:
  result |= 0xf << ((i - 1) << 2)
Ignacio Vazquez-Abrams