gpt4 book ai didi

Python 十六进制比较

转载 作者:太空狗 更新时间:2023-10-29 22:08:36 24 4
gpt4 key购买 nike

我遇到了一个问题,希望有人能帮我解决!

我有一个十六进制数 = '0x00000000' 的字符串,这意味着:

0x01000000 = apple  
0x00010000 = orange
0x00000100 = banana

与这些的所有组合都是可能的。即,0x01010000 = apple & orange

我如何从我的字符串中确定它是什么水果?我制作了一本包含所有组合的字典,然后与它进行比较,它起作用了!但我想知道更好的方法。

最佳答案

通过使用 int() 内置函数并指定基数,将字符串转换为整数:

>>> int('0x01010000',16)
16842752

现在,您有一个代表位集的标准整数。使用 &| 和任何其他按位运算符来测试各个位。

>>> 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

现在,如果您需要转换回您的字符串:

>>> hex(value)
'0x1000100'

关于Python 十六进制比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1888114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com