【问题标题】:Print Hex With Spaces Between打印带有空格的十六进制
【发布时间】:2019-01-29 03:49:06
【问题描述】:

我正在尝试以另一种方式打印我的十六进制...

首先我要转换这个(字节串是变量的名称):

b'\xff\x00\xff\xff\xff'

到十六进制,

print(bytestring.hex())

哪个输出:

ff00ffffff

但我已经尝试了一段时间让它输出这个:

ff 00 ff ff ff

但没有运气。

有什么建议吗? 干杯!


更新:

stringdata = f.read(5)
print(stringdata)
#b'\xff\x00\xff\xff\xff'

readHex = " ".join(["{:02x}".format(x) for x in stringdata.hex()])
# ValueError: Unknown format code 'x' for object of type 'str'

【问题讨论】:

  • b'\xff\x00\xff\xff\xff\' 是语法错误:最后一个反斜杠太多
  • @pault:如果你考虑十六进制字符串的中间步骤,是的,它可能是一个骗子,但对于整个问题来说,它不是
  • 当然-我在想btyestring = str(b'\xff\x00\xff\xff\xff').encode('hex') 然后你可以做" ".join([btyestring[i:i+2] for i in range(0, len(btyestring), 2)]) @Jean-FrançoisFabre

标签: python python-3.x hex


【解决方案1】:

只需将字节数组转换为十六进制字符串,然后用空格连接结果:

>>> d=b'\xff\x00\xff\xff\xff'
>>> " ".join(["{:02x}".format(x) for x in d])
'ff 00 ff ff ff'

请注意," ".join("{:02x}".format(x) for x in d) 也可以,但强制创建列表更快,如下所述:Joining strings. Generator or list comprehension?

在 python 2 中,bytesstr 所以你必须使用 ord 来获取字符代码

>>> " ".join(["{:02x}".format(ord(x)) for x in d])

【讨论】:

    【解决方案2】:

    在 Python 3.8+ 中,hex 函数有一个可选的参数拆分器。

    >>> print(b'\xff\x00\xff\xff\xff'.hex(' '))
    'ff 00 ff ff ff'
    

    你可以用你想要的任何字符分割十六进制字符串。

    >>> print(b'\xff\x00\xff\xff\xff'.hex(':'))
    'ff:00:ff:ff:ff'
    

    【讨论】:

    • 第二个参数设置每个分隔符的字节数,默认为 1。如果将其设为负数,则从右侧而不是左侧计算分隔符。 docs: hex([sep[, bytes_per_sep]])
    【解决方案3】:

    似乎社区不同意这是一个骗局,所以我将发布my comment 作为答案。

    你可以转换成字符串:

    bytestring = str(b'\xff\x00\xff\xff\xff').encode('hex')
    print(bytestring)
    #ff00ffffff
    

    然后iterate over it in chunks of 2,并用空格连接块:

    print(" ".join([bytestring[i:i+2] for i in range(0, len(bytestring), 2)]))
    #'ff 00 ff ff ff'
    

    【讨论】:

    • Python 3.8 中没有:LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
    【解决方案4】:

    您可以遍历字节字符串并在 python 中获取一系列字节。这些字节表示为整数。然后将它们转换回十六进制字符串并将它们全部连接在一起,每个十六进制字符串之间有一个空格。

    >>> a = b'\xff\x00\xff\xff'
    >>> print( ' '.join( '%02x' % x for x in a ) )
    'ff 00 ff ff'
    

    或者在python3中使用format

    >>> a = b'\xff\x00\xff\xff'
    >>> print( ' '.join( '{:02x}'.format(x) for x in a ) )
    'ff 00 ff ff'
    

    【讨论】:

    • 这与其他答案有何不同?
    • 不是,我是在 Jean-Francois 的回答同时添加的。我同意他的观点,加入列表推导可能比加入生成器推导更快。但我喜欢函数调用中生成器推导的优雅(如果你知道列表没有很多元素)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多