python pack和unpack的用法

#  按照给定的格式(fmt),把数据封装成字符串(实际上是类似于c结构体的字节流)

pack(fmt, v1, v2, ...) 

# 按照给定的格式(fmt)解析字节流string,返回解析出来的tuple

unpack(fmt, string)   

=======================================

>>> import struct
>>> struct.pack('>H',56)
'\x008'

>>> struct.unpack('>H','\x008')
(56,)


>>> struct.unpack('>H','\x008')[0]
56

====================

>>> struct.pack('@H', 56)
'8\x00'
>>> struct.unpack('@H', '8\x00')
(56,)
>>>
 

=====================

fmt格式为:

FORMATC TYPEPYTHON TYPESTANDARD SIZENOTES
xpad byteno value
ccharstring of length 11
bsigned charinteger1(3)
Bunsigned charinteger1(3)
?_Boolbool1(1)
hshortinteger2(3)
Hunsigned shortinteger2(3)
iintinteger4(3)
Iunsigned intinteger4(3)
llonginteger4(3)
Lunsigned longinteger4(3)
qlong longinteger8(2), (3)
Qunsigned long longinteger8(2), (3)
ffloatfloat4(4)
ddoublefloat8(4)
schar[]string
pchar[]string
Pvoid *integer(5), (3)

格式中的第一个字符来改变对齐方式(字节序).定义如下

CHARACTERBYTE ORDERSIZEALIGNMENT
@nativenativenative
=nativestandardnone
<little-endianstandardnone
>big-endianstandardnone
!network (= big-endian)standardnone
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在 Java 中,你可以使用 ByteBuffer 类来实现类似于 Pythonstruct 模块中的 pack 和 unpack 方法的功能。以下是一个示例代码: ```javaimport java.nio.ByteBuffer; import java.nio.ByteOrder; public class StructExample { public static void main(String[] args) { // 将 int 值打包为字节序列 int intValue =12345; byte[] packedBytes = packInt(intValue); System.out.println("Packed bytes: " + bytesToHex(packedBytes)); // 将字节序列解包为 int 值 int unpackedInt = unpackInt(packedBytes); System.out.println("Unpacked int: " + unpackedInt); } private static byte[] packInt(int value) { ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(ByteOrder.LITTLE_ENDIAN); // 设置字节序为小端序列(与Pythonstruct默认相同) buffer.putInt(value); return buffer.array(); } private static int unpackInt(byte[] bytes) { ByteBuffer buffer = ByteBuffer.wrap(bytes); buffer.order(ByteOrder.LITTLE_ENDIAN); // 设置字节序为小端序列 return buffer.getInt(); } private static String bytesToHex(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02X", b)); } return sb.toString(); } } ``` 上述代码演示了 Java 中如何实现类似于 Pythonstruct 模块中的 pack 和 unpack 方法。`packInt` 方法将一个 int 值打包为字节序列,`unpackInt` 方法将字节序列解包为一个 int 值。在这个示例中,我们使用了 ByteBuffer 类来处理字节操作,并通过设置字节序为小端序列来与 Pythonstruct 默认行为保持一致。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

字正腔圆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值