2010-05-31 107 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])。