[英]given two bits in a set of four, find position of two other bits
I am working on a simple combinatorics part, and found that I need to recover position of two bits given position of other two bits in 4-bits srring. 我正在研究一个简单的组合部分,发现在4位存储中给定其他两位的位置时,我需要恢复两位的位置。
for example, (0,1) maps to (2,3), (0,2) to (1,3), etc. for a total of six combinations. 例如,(0,1)映射到(2,3),(0,2)到(1,3)等,总共有六个组合。
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. 我必须澄清,不使用for循环,我的目标语言是C ++元编程模板。 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 谢谢
只需对二进制1111的值进行异或运算-这将翻转四位,为您提供另外两位。
cd = ab ^ 0xF;
The problem space is rather small, so a LUT-based solution is fast and easy. 问题空间很小,因此基于LUT的解决方案既快速又容易。
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.