原文链接: python struct 模块 字节数组 浮点数 相互转换
上一篇: windows10 远程桌面 访问 ubuntu16
下一篇: python matplot 动态绘图
c++ float 转字节
#include <cstdio>
int main(){
float x = 12.345;
char* p = (char*)&x;
printf("%d, %d, %d, %d\n",*p,*(p+1),*(p+2),*(p+3));
return 0;
}
31, -123, 69, 65
Python float 转字节
import struct
x = struct.pack('f', 12.345)
y = struct.unpack('4b', x)
print(x) # b'\x1f\x85EA'
print(y) # (31, -123, 69, 65)
python 字节数组转
import struct
b = [31, -123, 69, 65]
y = struct.unpack('<f', struct.pack('4b', *b))[0]
print(y)
12.345000267028809