简体   繁体   English

如何在Python中将字符串转换为十六进制字符串?

[英]How do I convert a string of bits to a hex string in Python?

I have a bit-string of 32 characters that I need to represent as hexadecimal in Python. 我有一个32位字符的位串,我需要在Python中表示为十六进制。 For example, the string "10000011101000011010100010010111" needs to also be output as "83A1A897" . 例如,字符串"10000011101000011010100010010111"也需要输出为"83A1A897"

Any suggestions on how to best go about this in Python? 关于如何在Python中最好地解决这个问题的任何建议?

To format to hexadecimal you can use the hex function: 要格式化为十六进制,可以使用十六进制函数:

>>> hex(int('10000011101000011010100010010111', 2))
0x83a1a897

Or to get it in exactly the format you requested: 或者以您要求的格式获得它:

>>> '%08X' % int('10000011101000011010100010010111', 2)
83A1A897
>>> binary = '10010111'
>>> int(binary,2)
151
>>> hex(int(binary,2))
'0x97'

I hope this helps! 我希望这有帮助!

You can do this very easy with build in functions. 通过内置函数,您可以轻松完成此任务。 The first thing you want to do is convert your binary to an integer: 您要做的第一件事是将二进制转换为整数:

>> int("1010",2)
10

The second step then would be to represent this as hex: 然后第二步是将其表示为十六进制:

>> "%04X" % int("1010",2)
'000A'

in case you don't want any predefined length of the hex string then just use: 如果你不想要任何预定义的十六进制字符串长度,那么只需使用:

>> "%X" % int("1010",2)
'A'
>> "0x%X" % int("1010",2)
'0xA'

Well we could string format just like Mark Byers said.Or in other way we could string format in another method like given below: 好吧,我们可以像Mark Byers所说的那样将字符串格式化。或者以其他方式我们可以将字符串格式化为另一种方法,如下所示:

>>> print('{0:x}'.format(0b10000011101000011010100010010111))
83a1a897

To make the alphabets between the hex in upper case try this: 要使大写字母之间的字母表为大写,请尝试:

>>> print('{0:X}'.format(0b10000011101000011010100010010111))
83A1A897

Hope this is helpful. 希望这是有帮助的。

To read in a number in any base use the builtin int function with the optional second parameter specifying the base (in this case 2). 要读入任何基数中的数字,请使用builtin int函数和可选的第二个参数指定基数(在本例中为2)。

To convert a number to a string of its hexadecimal form just use the hex function. 要将数字转换为其十六进制形式的字符串,只需使用hex函数。

>>> number=int("10000011101000011010100010010111",2)
>>> print hex(number)
0x83a1a897L

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

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