二进制反转

0 投票
2 回答
1299 浏览
提问于 2025-04-18 00:01

我想要找到一种最简单的方法来反转一个数字中特定的位,其中最左边的位是最低有效位(LSB)。

举个例子,如果我有一个函数 invert(n, b),当我执行 invert(15, 0) 时,它应该反转从左边数的第零位。如果我执行 invert(15, 1),它就会反转从左边数的第一位,依此类推。

2 个回答

-1

这可以通过取模运算来实现:

reverse_bin[x] = MOD(x+1,2)
1

如果你想要反转一个整数数字中特定的位,可以使用:

def flipBit (n, b): #n the number, b the bit, 0 = LSB
    return n ^ (1 << b)

如果你需要这个数字的字符串形式,可以用 bin(x)[2:]

举个例子:

def flipBit(n, b):
    return n ^ (1 << b)

def toBinStr(n):
    return bin(n)[2:]

y = 42
print('Number is {}.'.format(toBinStr(y)))
for x in range(8):
    print('Flipping bit {} gives {}.'.format (x, toBinStr(flipBit(y, x))))

你的例子:

#number that needs inversion
number = '1010'
#bit that needs to be inverted (first digit here)
bit_to_invert = 1

##code here##
inverted = bin(int(number, 2) ^ (1 << (bit_to_invert - 1)))[2:]

#this should output 1011
print inverted

撰写回答