LoginSignup
0
0

More than 1 year has passed since last update.

python 字节序

Last updated at Posted at 2021-06-01

阮一峰 - 理解字节序

获取字节顺序

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
https://stackoverflow.com/questions/7869752/javascript-typed-arrays-and-endianness

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0