base64转十六进制字符串

base64 to hex string

我正在尝试从 base64 字符串中生成十六进制字符串。 原始字符串为:M0SvYeRHPWDYVIG/giptBFqBMQdWObq8br1RDqWfO1rvky6RW0HiGCMQC1mhybYzFeSUkC5iw464P5nCYUc== 它应该变成:

3344af61e4473d60d85481bf822a6d04 5a8131075639babc6ebd510ea59f3b5a ef932e915b41e21823100b59a1c9b633 15e494902e62c38eb83f99c26147 

我的代码是:

str1 = "M0SvYeRHPWDYVIG/giptBFqBMQdWObq8br1RDqWfO1rvky6RW0HiGCMQC1mhybYzFeSUkC5iw464P5nCYUc=="
d = base64.b64decode(str1)
d1 = d.decode('utf-8')
print(d1)

但是,我在解码 utf-8 时收到消息:

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

d1的输出为:

b'3D\xafa\xe4G=`\xd8T\x81\xbf\x82*m\x04Z\x811\x07V9\xba\xbcn\xbdQ\x0e\xa5\x9f;Z\xef\x93.\x91[A\xe2\x18#\x10\x0bY\xa1\xc9\xb63\x15\xe4\x94\x90.b\xc3\x8e\xb8?\x99\xc2aG'

我的错误在哪里? 我还希望看到从十六进制字符串到 base64 的反向版本。 我用 python 3.

base64.b64decode(str1)的结果是:

  • 一个bytes对象已经在Python3.
  • a str object in Python 2(这里 strbytes 是同义词)。

以下 评论 脚本涵盖了两个 Python 版本:

import base64
str1 = "M0SvYeRHPWDYVIG/giptBFqBMQdWObq8br1RDqWfO1rvky6RW0HiGCMQC1mhybYzFeSUkC5iw464P5nCYUc=="
d = base64.b64decode(str1)
print(type(d))
print(type(d) is bytes)

# python 2
if type(d) is str:
    d = bytearray(d)

# The old format style was the %-syntax:
d1=''.join(['%02x'%i for i in d])
print(d1)

# The more modern approach is the .format method:
d1=''.join(['{:02x}'.format(i) for i in d])
print(d1)

结果:

py -3 .\SO3087693.py
<class 'bytes'>
True
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147
py -2 .\SO3087693.py
<type 'str'>
True
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147

注意:more recently, from Python 3.6 upwards there is a f-string syntax(但我已经冻结在 3.5.1 版本,因此无法通过示例证明):

''.join([f'{i:02x}' for i in d])