开发者

given two bits in a set of four, find position of two other bits

I am working on 开发者_如何学Pythona simple combinatorics part, and found that I need to recover position of two bits given position of other two bits in 4-bits srring.

for example, (0,1) maps to (2,3), (0,2) to (1,3), etc. for a total of six combinations.

My solution is to test bits using four nested ternary operators:

ab is a four bit string, with two bits set.
c = ((((ab & 1) ? (((ab & 2) ? ... ))) : 0)
abc = ab | c
recover the last bit in the same fashion from abc.

I have to clarify, without using for loops, my target language is C++ meta-programming templates. I know I specified language explicitly, but it's still agnostic in my opinion

can you think of a better way/more clever way? thanks


Just xor the value with binary 1111 - this will flip the four bits, giving you the other two.

cd = ab ^ 0xF;


The problem space is rather small, so a LUT-based solution is fast and easy.

Python:

fourbitmap = {
  3: (2, 3),
  5: (1, 3),
  6: (0, 3),
  9: (1, 2),
  10: (0, 2),
  12: (0, 1),
}

def getother2(n):
  return fourbitmap.get(n, None)


Python:

def unset_bits(input=0x5):
    for position in range(4):
        if not (2**position) & input:
            yield position

Yields:

>>> list( unset_bits(0x1) )
[1, 2, 3]

>>> list( unset_bits(0x2) )
[0, 2, 3]

>>> list( unset_bits(0x3) )
[2, 3]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜