Python 十六进制比较
我遇到了一个问题,希望有人能帮我解决!
我有一个十六进制数字 = '0x00000000'
的字符串,这意味着:
0x01000000 = apple
0x00010000 = orange
0x00000100 = banana
与这些的所有组合都是可能的。即,0x01010000 = 苹果 & Orange
我如何从我的字符串中确定它是什么水果?我用所有组合制作了一本字典,然后与它进行比较,它起作用了!但我想知道一种更好的方法。
I got a problem I was hoping someone could help me figure out!
I have a string with a hexadecimal number = '0x00000000'
which means:
0x01000000 = apple
0x00010000 = orange
0x00000100 = banana
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过使用
int()
内置函数并指定基数,将字符串转换为整数:现在,您有了一个表示位集的标准整数。使用
&
、|
和任何其他按位运算符来测试各个位。现在,如果您需要转换回字符串:
Convert your string to an integer, by using the
int()
built-in function and specifying a base:Now, you have a standard integer representing a bitset. use
&
,|
and any other bitwise operator to test individual bits.Now, if you need to convert back to your string:
您可以首先将字符串转换为整数:
然后,您可以为水果设置一个列表:
用于确定您有哪些水果就足够了:
这里的输出是:
You could first of all convert your string to an integer:
then, you could set up a list for the fruits:
for determing what fruits you have that is enough:
The output here is: