如何使python中的所有位都反转?
我想如下转换这些二进制表示如何使python中的所有位都反转?,python,math,binary,bit,Python,Math,Binary,Bit,我想如下转换这些二进制表示 "1111" -> "0000" "1010" -> "0101" 希望你看起来像这样 def convert(inp): return ''.join(['1','0'][int(i)] for i in inp) convert('1010') 输出 0101 我有一个方法可以做到这一点,但它需要几个类型转换。不确定是否有更好的方法来做到这一点 def f(x:str): return '%04d' % int(bin(int(
"1111" -> "0000"
"1010" -> "0101"
希望你看起来像这样
def convert(inp):
return ''.join(['1','0'][int(i)] for i in inp)
convert('1010')
输出
0101
我有一个方法可以做到这一点,但它需要几个类型转换。不确定是否有更好的方法来做到这一点
def f(x:str):
return '%04d' % int(bin(int(x, 2) ^ 15)[2:])
print(f("0000"))
print(f("0011"))
print(f("1010"))
print(f("1111"))
我不擅长python,但我认为这是正确的,因为它在我的计算机上工作
num = input()
answer = ""
for i in range(0, len(num)):
if num[i] == "0":
answer += "1"
elif num[i] == "1":
answer += "0"
print(answer)
输入:
0000
输出:
1111
转化
"0100" to "1011", simply 0100(your input string) ^ 1111(maskbit) = "1011"
"11110000" to "00001111", simply 11110000(your input string) ^ 11111111(maskbit) = "00001111"
我们可以在这里看到一种模式
len(掩码位)=len(二进制输入字符串)
根据上述观察,
def invertBits(num):
mask='1'*len(num) #This produces bit mask needed for the conversion
answer=int(num,2)^int(mask,2) #Inversion process happens here (XOR)
print(answer,bin(answer).lstrip("0b")); #This would give both the integer equivalent and the pattern of the inverted bits as a string
invertBits("0100") #The output will be "11 1011"
方法
int(num,2)
将“num
”参数作为字符串,并在此处使用base=“2
”(二进制格式),因为我不想在字符串中循环。转换为int,用15进行异或,然后转换回二进制字符串。这是否回答了您的问题?听起来你想要一个接受整数并返回整数的函数;是这样吗?或者您真的想要获取并返回一个字符串吗?两者都是find,因为它可以转换为整数,反之亦然。
def invertBits(num):
mask='1'*len(num) #This produces bit mask needed for the conversion
answer=int(num,2)^int(mask,2) #Inversion process happens here (XOR)
print(answer,bin(answer).lstrip("0b")); #This would give both the integer equivalent and the pattern of the inverted bits as a string
invertBits("0100") #The output will be "11 1011"