我需要最简洁的方法来反转数字中的特定位,其中最左边的位是LSB。二进制反转
例如,如果我有一个功能invert(n, b)
并且我要执行invert(15, 0)
,它应该从左侧反转第零位。如果我是执行invert(15, 1)
将倒置从左边的第一个数字,等
我需要最简洁的方法来反转数字中的特定位,其中最左边的位是LSB。二进制反转
例如,如果我有一个功能invert(n, b)
并且我要执行invert(15, 0)
,它应该从左侧反转第零位。如果我是执行invert(15, 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
我试过用你的flipBit函数,它效果很好!我也更喜欢字符串上的整数。我唯一的问题是我如何使0代替LSB的MSB? – Quojil
你的意思是让1 LSB而不是0 LSB?因为这是您在示例I/O中所做的事情?如果0是MSB,你的例子将产生1110. – Hyperboreus
对不起,我不小心做了这个不清楚。示例IO应该输出0010.我会在OP中纠正它。 – Quojil
你能提供样本的输入和输出? – Hyperboreus
@Hyperboreus on – Quojil
我已更新我的答案并添加了您的示例。 – Hyperboreus