英文:
binary encoding Little endian in python
问题
我通常使用golang进行实现,现在我需要实现一个Python项目。我有以下指令(Golang):
import "encoding/binary"
arBytes := make([]byte, 16)
_, err := rand.Read(arBytes)
if err != nil {
return false, err
}
a0 = binary.LittleEndian.Uint64(arBytes[0:8])
我需要编写这些指令的Python版本,但是我找不到任何方法来从Uint64创建一个小端字节序的数组。是否有任何可用的解决方案可以帮助我!
英文:
I usually use golang for implementations and I need to implement a python project. I have the following instructions (Golang)
import "encoding/binary"
arBytes := make([]byte, 16)
_, err := rand.Read(arBytes)
if err != nil {
return false, err
}
a0 = binary.LittleEndian.Uint64(arBytes[0:8])
I need to write the python's version for these instructions but i do not found any way to create an array of little Endian from Uint64. Is there any available solution that can help!
答案1
得分: 0
等效的Python程序如下所示。
- 使用
secrets.token_bytes(16)
生成16个随机字节,类似于rand.Read(arBytes)
。 - 然后使用
int.from_bytes(..., "little")
将该字节数组解释为小端整数。from_bytes
默认为无符号值。
import secrets
b = secrets.token_bytes(16)
val = int.from_bytes(b[:8], "little")
英文:
The equivalent Python program would be as follows.
- Use
secrets.token_bytes(16)
to generate 16 random bytes, likerand.Read(arBytes)
would. - Then use
int.from_bytes(..., "little")
on that byte array to interpret the bytes as a little-endian integer.from_bytes
defaults to unsigned values.
import secrets
b = secrets.token_bytes(16)
val = int.from_bytes(b[:8], "little")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论