2010-05-31 33 views
1

我有一个8位十六进制数字,我需要某些数字是0或f。考虑到数字的具体位置,可以快速生成十六进制数字,并将这些地方“翻转”到f。例如:以十六进制位翻转

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

我的嵌入式设备上这样做,所以我不能调用任何数学库,我怀疑这是可以做到只用位移位,但我不能完全弄清楚的方法。任何类型的解决方案(Python,C,Pseudocode)都可以工作。提前致谢。

回答

4
result = 0 
for i in inputs: 
    result |= 0xf << ((i - 1) << 2) 
4

可以定义8个命名变量,每一个给定的四位设置所有位:

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

然后你可以使用按位或将它们结合起来:

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

如果你想要将它们在运行时组合起来,将常量存储在数组中可能最为简单,因此可以更容易地访问这些常量(例如,n[0] | n[6] | n[7])。