简体   繁体   English

给定四位一组中的两位,找到另外两位的位置

[英]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.

相关问题 如何查找给定范围内的整数数甚至设置了位 - How to find number of integers in a given range has even set bits 从两个流中找出匹配位和不匹配位的算法 - Algorithm to find out matched bits and non matched bits from two streams 枚举位向量使得不会同时设置两个相邻位的有效方法 - Effecient way to enumerate bit vectors such that no two adjacent bits are set simultaneously XOR 包含少于两个集合位的子集数 - Number of subsets whose XOR contains less than two set bits 清除一个字中除了两个最重要的设置位之外的所有位 - clear all but the two most significant set bits in a word 查找所有小于给定 no 且设置位数少于给定 no 但在同一 position 中的数字 - Finding all numbers which are less than a given no with less no of set bits than the given no but in the same position 确定BITS的总和 - sum of BITS is given find thar number 给定两个 32 位数字 N 和 M,以及两个位位置 i 和 j。 编写一个方法,将 N 中 i 和 j 之间的所有位设置为 M - Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M 连接两个数字的位的代码不起作用 - Code to concatenate two numbers' bits not working 查找使用2个设置位形成的第n个数字 - Find the nth number formed using 2 set bits
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM