阮一峰 - 理解字节序
获取字节顺序
import sys
endianness = sys.byteorder
print("system Endianness is "+ endianness)
大小端转换
"6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000".decode('hex')[::-1].encode('hex_codec')
#=> 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
import struct
ver = 1
prev_block = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
mrkl_root = "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098"
time = 1231469665
bits = 486604799
nonce = 2573394689
struct.pack("<L", ver) #转换为 unsigned long型小端
prev_block.decode('hex')[::-1] # 转换为16进制并大小端转换
mrkl_root.decode('hex')[::-1] # 转换为16进制并大小端转换
struct.pack("<LLL", time, bits, nonce) # 把3个变量转换为 unsigned long型小端
struct
在struct中有以下几种字节顺序
Character | Byte order | Size | Alignment |
---|---|---|---|
@ | native | native | native |
= | native | standard | none |
< | little-endian | standard | none |
> | big-endian | standard | none |
! | network (= big-endian) | standard | none |
字符 | 字节顺序 | 尺寸 | 对齐方式 |
---|---|---|---|
@ | 本机 | 本机 | 本机 |
= | 本机 | 标准 | 无 |
< | 小端 | 标准 | 无 |
> | 大端 | 标准 | 无 |
! | 网络即大端 | 标准 | 无 |
数据格式
Format | C Type | Python type | Standard size | Notes |
---|---|---|---|---|
x | pad byte | no value | ||
c | char | bytes of length 1 | 1 | |
b | signed char | integer | 1 | (1),(3) |
B | unsigned char | integer | 1 | (3) |
? | _Bool | bool | 1 | (1) |
h | short | integer | 2 | (3) |
H | unsigned short | integer | 2 | (3) |
i | int | integer | 4 | (3) |
I | unsigned int | integer | 4 | (3) |
l | long | integer | 4 | (3) |
L | unsigned long | integer | 4 | (3) |
q | long long | integer | 8 | (2), (3) |
Q | unsigned long | |||
long | integer | 8 | (2), (3) | |
n | ssize_t | integer | (4) | |
N | size_t | integer | (4) | |
e | (7) | float | 2 | (5) |
f | float | float | 4 | (5) |
d | double | float | 8 | (5) |
s | char[] | bytes | ||
p | char[] | bytes | ||
P | void * | integer | (6) |
字符 | C类型 | python类型 | 标准尺寸 |
---|---|---|---|
x | 填充字节 | 没有意义的值 | |
c | char | 长度为1的字节 | 1 |
b | signed char | 整型 | 1 |
B | unsigned char | 整型 | 1 |
? | _Bool | 布尔 | 1 |
h | short | 整型 | 2 |
H | unsigned short | 整型 | 2 |
i | int | 整型 | 4 |
I | unsigned int | 整型 | 4 |
l | long | 整型 | 4 |
L | unsigned long | 整型 | 4 |
q | long long | 整型 | 8 |
Q | unsigned long long | 整型 | 8 |
n | ssize_t | 整型 | |
N | size_t | 整型 | |
e | 浮动 | 2 | |
f | float | 浮动 | 4 |
d | double | 浮动 | 8 |
s | char[] | 字节 | |
p | char[] | 字节 | |
P | void * | 整型 |
参考:
https://en.wikipedia.org/wiki/Endianness
https://docs.python.org/3/library/struct.html
https://blog.csdn.net/youand_me/article/details/78890316
网友评论