Python十六进制比较 [英] Python hexadecimal comparison
问题描述
我遇到了一个问题,希望有人能帮助我找出答案!
I got a problem I was hoping someone could help me figure out!
我有一个字符串,十六进制数= '0x00000000'
,这意味着:
I have a string with a hexadecimal number = '0x00000000'
which means:
0x01000000 = apple
0x00010000 = orange
0x00000100 = banana
所有这些组合都是可能的.即 0x01010000 = apple&橙色
All combinations with those are possible. i.e., 0x01010000 = apple & orange
如何从字符串中确定它是什么水果?我制作了包含所有组合的字典,然后将其与之进行比较,就可以了!但是我想知道一种更好的方法.
How can I from my string determine what fruit it is? I made a dictionary with all the combinations and then comparing to that, and it works! But I am wondering about a nicer way of doing it.
推荐答案
通过使用内置的 int()
函数并指定基数,将字符串转换为整数:
Convert your string to an integer, by using the int()
built-in function and specifying a base:
>>> int('0x01010000',16)
16842752
现在,您有了一个代表位集的标准整数.使用&
, |
和任何其他按位运算符来测试各个位.
Now, you have a standard integer representing a bitset. use &
, |
and any other bitwise operator to test individual bits.
>>> value = int('0x01010000',16)
>>> apple = 0x01000000
>>> orange = 0x00010000
>>> banana = 0x00000100
>>> bool(value & apple) # tests if apple is part of the value
True
>>> value |= banana # adds the banana flag to the value
>>> value &= ~orange # removes the orange flag from the value
现在,如果您需要转换回字符串:
Now, if you need to convert back to your string:
>>> hex(value)
'0x1000100'
这篇关于Python十六进制比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!