如何有效地将 int 存储为字节? [英] How to efficiently store an int into bytes?

查看:76
本文介绍了如何有效地将 int 存储为字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用 python 3.7 套接字库来发送和接收信息的程序,我希望它在网络方面是高效的(不需要那么快,我没有足够的时间来构建它在 C) 中意味着如果我想发送数字 1024,我只需要 2 个字节.

在 C 中,所有需要做的就是将 int 转换为字符串,访问前 2 个字节,即(2 字节数字到 2 字节数组/字符串").

在 Python 中,即使使用字节结构,我也总是以 b'(\x8a',明显大于所需的字节数.

socket.send 函数只接受字节对象,所以我尝试将 int 解析为这样(to_bytes 和 from_bytes),但最终得到的字节数(b'(\x8a')比我使用的还要多str()

当我将接收缓冲区设置为 2 个字节以接收 1024 之类的数字时,我想接收 1024 而不是 10.

解决方案

如果要将数字打包成字节,则需要 struct 模块.

<预><代码>>>>struct.pack('>H', 1024)b'\x04\x00'

这将数据 1024 打包成一个 unsigned short aka uint16_t (H),在大-字节序格式 (>).这给出了两个字节 04 00.

在实践中,struct通常用于将大量数据打包在一起,使用更长的格式字符串:

data = struct.pack('>bbbbHHiid', dat1, dat2, dat3...)

您现在可能明白为什么该模块得名了!

如果你真的只需要发送一个数字,你可以使用内置的int.to_bytes方法:

<预><代码>>>>(1024).to_bytes(2, '大')b'\x04\x00'

第一个参数是要使用的字节数,第二个是字节序.

I am developing a program that uses the python 3.7 socket library to send and receive information, and I want it to be efficient network wise (doesn't need to be all that fast, I don't have enough time to build it in C) meaning if I want to send the number 1024, I should only need 2 bytes.

In C, all that needs to be done is cast the int as a string, access the first 2 bytes and that is that (2 byte number to a 2 byte array/"string").

In Python, even when using the bytes structures, I always end up with something of the sort b'(\x8a', which is significantly larger than the needed byte amount.

The socket.send function only accepts byte objects, so I tried parsing the int as so (to_bytes and from_bytes), but ended up with an even bigger amount of bytes (b'(\x8a') than if I had used str()

When I set the receive buffer to 2 bytes for a number like 1024, I want to receive 1024 and not 10.

解决方案

If you want to pack numbers into bytes, you'll want the struct module.

>>> struct.pack('>H', 1024)
b'\x04\x00'

This packs the data 1024 into a single unsigned short aka uint16_t (H), in big-endian format (>). This gives the two bytes 04 00.

In practice, struct is usually used to pack a lot of data together, using longer format strings:

data = struct.pack('>bbbbHHiid', dat1, dat2, dat3...)

You probably see now why that module gets its name!

If you really only need to send a single number, you can use the built-in int.to_bytes method:

>>> (1024).to_bytes(2, 'big')
b'\x04\x00'

The first argument is the number of bytes to use, the second is the endianness.

这篇关于如何有效地将 int 存储为字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆