繁体   English   中英

如何在 Python 中获取 5 位十六进制字符串?

[英]How can I get the string of 5 digit hexadecimal in Python?

我有一个 integer 转换为十六进制,如下所示:

  int_N = 193402
  hex_value = hex(int_N)

它给了我以下十六进制: 0x2f37a

我想将十六进制转换为字符串

我试过这个:

  bytes.fromhex(hex_value[2:]).decode('ASCII')
  # [2:] to get rid of the 0x

但是,它给了我这个错误:

   UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position 1: ordinal not in range(128)

然后我尝试使用decode('utf-8') 而不是 ASCII ,但它给了我这个错误:

   UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 1: invalid start byte

有什么建议可以解决这个问题吗? 为什么它没有将十六进制 '0x2f37a' 转换为字符串?

在阅读了一些文档之后,我认为十六进制可能应该包含偶数个数字才能转换为字符串,但由于我使用的是 hex() 并且它给了我这个值,所以我无法这样做或做到这一点。

感谢并非常感谢任何帮助!

我假设(可能是错误的)您的 int_N 是 unicode 代码点。

>>> int_N = 193402
>>> chr(int_N)
'\U0002f37a'

您应该查看 struct 和 binascii 模块。

import struct
import binascii

int_N = 193402

s      = struct.Struct(">l")
val    = s.pack(int_N)
output = binascii.hexlify(val)

print(output) #0002f37a

在 PMOTW3了解更多关于 c_type 打包的信息。

如果您只是想将其转换为字符串,没有其他要求,那么这是可行的(我将在此处将其填充为 8 个字符):

int_N = 193402
s = hex(int_N)[2:].rjust(8, '0') # get rid of '0x' and pad to 8 characters
print(s, type(s))

Output:

0002f37a <class 'str'>

...证明它是一个字符串类型。 如果您对获取单个字节感兴趣,那么这样的事情将证明:

for b in bytes.fromhex(s):
    print(b, type(b))

Output:

0 <class 'int'>
2 <class 'int'>
243 <class 'int'>
122 <class 'int'>

...显示所有四个字节(来自八个十六进制数字)并证明它们是整数。 这里的关键是偶数个字符,我选择了 8) 以便fromhex()可以对其进行解码。 奇数字节将给出ValueError

现在您可以随意使用字符串或字节。

使用 f 字符串(格式字符串)以您喜欢的方式格式化数字。 以下是十六进制和二进制的各种 forms 的示例:

>>> n=193402
>>> f'{n:x} {n:08x} {n:#x} {n:020b}'
'2f37a 0002f37a 0x2f37a 00101111001101111010'

请参阅格式规范迷你语言

暂无
暂无

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

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