【问题标题】:How can I get the string of 5 digit hexadecimal in Python?如何在 Python 中获取 5 位十六进制字符串?
【发布时间】:2021-12-29 18:31:34
【问题描述】:

我有一个整数,我按如下方式转换为十六进制:

  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() 它给了我价值。

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

【问题讨论】:

  • hex_value[2:] 不适合你吗?
  • 因为type(hex_value)告诉我已经是str
  • 那里没有真正的问题。请说明您的要求。
  • @intedgarhex_value[2:] 有效,它给了我 2f37a。但是当我想获取字符串时它不起作用。
  • @VoNWooDSoN 如何将十六进制 0x2f37a 转换为字符串?

标签: python encryption utf-8 hex


【解决方案1】:

你应该看看 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

详细了解 c_type 打包here at PMOTW3

【讨论】:

    【解决方案2】:

    如果您只是想将其转换为字符串,没有其他要求,那么它可以工作(我将其填充为 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))
    

    输出:

    0002f37a <class 'str'>
    

    ...证明它是一个字符串类型。如果您对获取单个 bytes 感兴趣,那么下面的内容将展示:

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

    输出:

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

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

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

    【讨论】:

      【解决方案3】:

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

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

      Format Specification Mini-Language

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-16
        • 2019-07-27
        • 2011-07-02
        • 2023-04-08
        相关资源
        最近更新 更多