Skip to content

Commit ec8a58e

Browse files
committed
6.9小节完成
1 parent 2def1e7 commit ec8a58e

File tree

2 files changed

+82
-4
lines changed

2 files changed

+82
-4
lines changed

cookbook/c06/p09_codec_hex.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#!/usr/bin/env python
2+
# -*- encoding: utf-8 -*-
3+
"""
4+
Topic: 编码/解码十六进制原始字符串
5+
Desc :
6+
"""
7+
import binascii
8+
import base64
9+
10+
11+
def codec_hex():
12+
s = b'hello'
13+
# Encode as hex
14+
h = binascii.b2a_hex(s)
15+
print(h)
16+
# Decode back to bytes
17+
h = binascii.a2b_hex(h)
18+
print(h)
19+
20+
# 使用base64模块也可以
21+
h = base64.b16encode(s)
22+
print(h)
23+
print(h.decode('ascii'))
24+
h = base64.b16decode(h)
25+
print(h)
26+
print(h.decode('ascii'))
27+
28+
29+
if __name__ == '__main__':
30+
codec_hex()
Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,66 @@
11
============================
2-
6.9 编码解码十六进制数
2+
6.9 编码和解码十六进制数
33
============================
44

55
----------
66
问题
77
----------
8-
todo...
8+
你想将一个十六进制字符串解码成一个字节字符串或者将一个字节字符串编码成一个十六进制字符串。
9+
10+
|
911
1012
----------
1113
解决方案
1214
----------
13-
todo...
15+
如果你只是简单的解码或编码一个十六进制的原始字符串,可以使用 ``binascii`` 模块。例如:
16+
17+
.. code-block:: python
18+
19+
>>> # Initial byte string
20+
>>> s = b'hello'
21+
>>> # Encode as hex
22+
>>> import binascii
23+
>>> h = binascii.b2a_hex(s)
24+
>>> h
25+
b'68656c6c6f'
26+
>>> # Decode back to bytes
27+
>>> binascii.a2b_hex(h)
28+
b'hello'
29+
>>>
30+
31+
类似的功能同样可以在 ``base64`` 模块中找到。例如:
32+
33+
.. code-block:: python
34+
35+
>>> import base64
36+
>>> h = base64.b16encode(s)
37+
>>> h
38+
b'68656C6C6F'
39+
>>> base64.b16decode(h)
40+
b'hello'
41+
>>>
42+
43+
|
1444
1545
----------
1646
讨论
1747
----------
18-
todo...
48+
大部分情况下,通过使用上述的函数来转换十六进制是很简单的。
49+
上面两种技术的主要不同在于大小写的处理。
50+
函数 ``base64.b16decode()`` 和 ``base64.b16encode()`` 只能操作大写形式的十六进制字母,
51+
而 ``binascii`` 模块中的函数大小写都能处理。
52+
53+
还有一点需要注意的是编码函数所产生的输出总是一个字节字符串。
54+
如果想强制以Unicode形式输出,你需要增加一个额外的界面步骤。例如:
55+
56+
.. code-block:: python
57+
58+
>>> h = base64.b16encode(s)
59+
>>> print(h)
60+
b'68656C6C6F'
61+
>>> print(h.decode('ascii'))
62+
68656C6C6F
63+
>>>
64+
65+
在解码十六进制数时,函数 ``b16decode()`` 和 ``a2b_hex()`` 可以接受字节或unicode字符串。
66+
然而,这些字符串必须仅仅只包含ASCII编码的十六进制数。

0 commit comments

Comments
 (0)