简体   繁体   English

如何在Python中将一个字节的int更改为两个字节?

[英]How to change one byte int to two bytes in Python?

I am making a basic server/client program, and I am making the client in Python. 我正在制作一个基本的服务器/客户端程序,并且正在使用Python制作客户端。 I have to format the message before I send it. 我必须先格式化邮件,然后再发送。 The first field is for message length. 第一个字段用于消息长度。 I can compute the message length, but I need to store the value in the first two bytes of my bytearray. 我可以计算消息的长度,但是我需要将值存储在字节数组的前两个字节中。 If the message length is less than 256, it should be only one byte. 如果消息长度小于256,则它应仅为一个字节。 How can I force the number to be 2 bytes without just tacking a 0x00 onto the front? 如何在不将0x00附加到前面的情况下将数字强制为2个字节?

Use the struct module . 使用struct模块 For example, to pack an integer into an unsigned two-byte value in network order (big-endian), you would do this: 例如,要将整数按网络顺序(big-endian)打包成无符号的两个字节的值,您可以这样做:

> my_value = 1234
> packed_bytes = struct.pack('>H', my_value)
> print packed_bytes
'\x04\xd2'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM