如何使python中的所有位取反?
How to make all the bits inverted in python?
我想将这些二进制表示转换如下。
"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"))
output:
1111
1100
0101
0000
我不擅长 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(mask bit) = len(binary input string)
基于以上观察,
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
"(二进制格式)
我想将这些二进制表示转换如下。
"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"))
output:
1111
1100
0101
0000
我不擅长 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(mask bit) = len(binary input string)
基于以上观察,
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
"(二进制格式)