python主机字节转网络序

2018-09-04  本文已影响0人  你猜_19ca

百度简介

网络传输一般采用大端序,也被称之为网络字节序,或网络序,即先发送高字节数据再发送低字节数据(如:四个字节由高位向低位用0-31标示后,将首先发送0-7位第一字节,在发送8-15第二字节,以此下去)。IP协议中定义大端为网络字节序

伯克利socket API定义了一组转换函数,用于16和32bit整数在网络序和本机字节序之间的转换。htonl,htons用于本机序转换到网络序;ntohl,ntohs用于网络序转换到本机序。

解决方案

采用socket、struct
socket: 用于转换网络序
struct: 对python基本类型值与用python字符串格式表示的C struct类型间的转化

附赠struct打包格式表

Format C Type Python type Standard size Notes
x pad byte no value
c char string of length 1 1
b signed char integer 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)
f float float 4 (4)
d double float 8 (4)
s char[] string
p char[] string
P void * integer (5), (3)
上一篇下一篇

猜你喜欢

热点阅读