File tree Expand file tree Collapse file tree 2 files changed +82
-4
lines changed Expand file tree Collapse file tree 2 files changed +82
-4
lines changed Original file line number Diff line number Diff line change
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 ()
Original file line number Diff line number Diff line change 1
1
============================
2
- 6.9 编码解码十六进制数
2
+ 6.9 编码和解码十六进制数
3
3
============================
4
4
5
5
----------
6
6
问题
7
7
----------
8
- todo...
8
+ 你想将一个十六进制字符串解码成一个字节字符串或者将一个字节字符串编码成一个十六进制字符串。
9
+
10
+ |
9
11
10
12
----------
11
13
解决方案
12
14
----------
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
+ |
14
44
15
45
----------
16
46
讨论
17
47
----------
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编码的十六进制数。
You can’t perform that action at this time.
0 commit comments