[英]Return non- string number from the output of hex to binary conversion?
How can i get return value after converting hex value to binary string? 将十六进制值转换为二进制字符串后,如何获得返回值?
I'm always getting string binary which is not useful for bit operation. 我总是得到二进制字符串,这对位操作没有用。
ie bin(int(str('0x460001'), 16))
is always 0b10001100000000000000001
, instead I want 0b10001100000000000000001
as my output. 即
bin(int(str('0x460001'), 16))
始终为0b10001100000000000000001
,我希望将0b10001100000000000000001
作为我的输出。
For that binary value I want to perform an operation which requires non string value, like: 对于该二进制值,我想执行需要非字符串值的操作,例如:
0b10001100000000000000001 | 0b10001100100000000000001
Please let me know if there is any option or library I can use for it. 请让我知道我是否可以使用任何选项或库。
Probably to your surprise the problem you see isn't a problem at all because: 可能令您惊讶的是,您看到的问题根本不是问题,因为:
print( type(0b10001100100011000000001) )
# gives: <class 'int'> (or int in Python 2)
0b10001100100011000000001
IS a NUMBER, not a string ... so you can do binary operations directly with it. 0b10001100100011000000001
是一个数字,而不是字符串...因此您可以直接使用它执行二进制操作。
Just try this: 尝试一下:
print( 0x460001 == 0b10001100000000000000001 ) # gives True
print( 0x460001 == 4587521 ) # gives also True
print( 4587521 == 0b10001100000000000000001 ) # gives True
or this: 或这个:
print( type(0x460001), type(0b10001100000000000000001), type(4587521) )
# gives <class 'int'> <class 'int'> <class 'int'>
It doesn't matter HOW you write a number it will be the same number, but 不管如何写一个数字都将是相同的数字,但是
print( "0x460001" == 0b10001100000000000000001 ) # gives False
will give you False
as "0x460001"
is a string not a number. 会给您
False
因为"0x460001"
是字符串而不是数字。
Anyway, until you understand the above, you can play around with following code snippets: 无论如何,在您理解上述内容之前,您可以使用以下代码段:
def bitwiseORforBinaryNumbers(bin1, bin2):
return bin( bin1 | bin2 )
print( bitwiseORforBinaryNumbers(
0b10001100000011000000001,
0b10001100100000000000001) )
# 0b10001100100011000000001
or just written directly: 或直接写成:
print(
bin( 0b10001100000011000000001 |
0b10001100100000000000001 ) )
# 0b10001100100011000000001
The same for strings with binary representations of a number look like: 具有数字二进制表示形式的字符串也是如此:
def bitwiseORforStringsWithBinaryValue(binStr1, binStr2):
return bin(int(binStr1,2) | int(binStr2,2))
print( bitwiseORforStringsWithBinaryValue("0b10001100000011000000001", "0b10001100100000000000001") )
# gives:
0b10001100100011000000001
or just done directly in code: 或直接在代码中完成:
print( bin( int("0b10001100000011000000001",2) | int("0b10001100100000000000001",2) ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.