简体   繁体   English

在python中将int转换为字节流

[英]Converting int to byte streams in python

I am new to python so please bear with if it sounds a novice question. 我是python的新手,所以如果它是一个新手问题,请耐心等待。 I looked it up but different sources tell me different things so I decided to ask it here. 我查了一下,但是不同的消息来源告诉我不同​​的事情,所以我决定在这里问。 And doc is not very clear. 和文档不是很清楚。

I have an int that I want to convert to bytes. 我有一个要转换为字节的整数。

#1024 should give me 0000010000000000
print bytes([1024])
[1024]

If I use bytes() I assume I get a list since when I print I end up getting [1024]. 如果我使用bytes(),我认为我会得到一个列表,因为打印时我最终会得到[1024]。 However if I do 但是如果我这样做

print bytes([1024])[0] 
[

I get [ back. 我回来了。 Why is this? 为什么是这样? So it does not return a list? 因此它不返回列表吗?

Is there a way to get the byte streams back given an integer? 有没有办法让整数返回字节流? Ideally I want something as follows: 理想情况下,我需要以下内容:

x = tobyte(1024)
print x[0] #should give me  0  00000000
print x[1] #should give me  8  00000100

I need to be able to use x[0] elsewhere in the code ie to be passed to base64 encode where I expect my data to be 64 bits 我需要能够在代码的其他地方使用x [0],即传递给base64编码,我希望我的数据为64位

To get the individual bytes from an integer, use struct : 要从整数获取单个字节,请使用struct

individual_bytes = struct.unpack("BB", struct.pack("<H", 1024))

First, "<I" packs the integer as a 16-bit value, using little-endian ordering. 首先, "<I"使用little-endian排序将整数打包为16位值。 Then "BB" unpacks the byte string into two separate 8-bit values. 然后, "BB"将字节字符串解压缩为两个单独的8位值。

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

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