简体   繁体   English

直接在python中使用位

[英]Using bits directly in python

I want to manipulate the binary number directly in python. 我想直接在python中操作二进制数。 For example I have decimal number 18. I was able to convert number into binary using 例如,我有十进制数字18。我能够使用

seed =bin(18)

but problem is I want to xor few of its bits.If I access this seed using array indexing I cant xor them as it is of type 'str'. 但是问题是我想对其进行异或运算。如果我使用数组索引访问该种子,我将无法对其进行异或运算,因为它的类型为'str'。 How can simply take decimal number convert into binary and play with its bits? 如何简单地将十进制数转换为二进制并使用其位?

Thanks in advance 提前致谢

You can use bitwise operators directly on numbers. 您可以直接在数字上使用按位运算符。

For instance 18 & 3 gets you 2 , 18 | 3 例如18 & 3让你218 | 3 18 | 3 gets you 19 , 1 << 5 gets you 32 . 18 | 3让你191 << 5让你32 The fact that the human readable representation when you print the number is a decimal number doesn't change the fact that at an underlying level the numbers are all just stored and operated on as binary numbers. 当您打印数字时,人类可读的表示形式是一个十进制数字这一事实并没有改变以下事实:在底层,数字都只是作为二进制数字存储和操作。

bin just gives you the binary representation of a number as a string. bin只是将数字的二进制表示形式表示为字符串。 While that's useful for debugging or human output, you generally won't want to use it for bit manipulation directly. 尽管这对于调试或人工输出很有用,但是您通常不希望将其直接用于位操作。

You can use bitwise operations directly on integers. 您可以直接对整数使用按位运算。 You can convert between binary strings and integers for printing/debugging by using bin as you already know, and converting a string to binary using int(binary_string, 2) . 您可以通过使用bin来在二进制字符串和整数之间进行转换,以进行打印/调试,并使用int(binary_string, 2)将字符串转换为二进制。

seed = bin(18)  # 0b10010
bitmask = '01101'
xor_result = 18 ^ int(bitmask, 2)
print(bin(xor_result))  # 0b11111

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM