将readBin R转换为Python

2024-06-28 10:57:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一些使用readBin函数(R)的代码转换成Python。在

R代码:

datFile = file("https://stats.idre.ucla.edu/stat/r/faq/bintest.dat", "rb")
i<-readBin(datFile, integer(), n = 4, size=8, endian = "little", signed=FALSE)
print(i)

退货:

^{pr2}$

我在Python中的尝试:

^{3}$

退货:

8589934593

如何在Python中获得相同的输出(我知道我缺少n参数,但我找不到正确实现它的方法)。在

谢谢


Tags: 函数代码httpsstatsstatdatfilefaq
1条回答
网友
1楼 · 发布于 2024-06-28 10:57:48

试试这个:

with open("bintest.dat", "rb") as f:
    # this is exactly the same as 'n = 4' in R code
    n = 4
    count = 0
    byte = f.read(4)
    while count < n and byte != b"":
        i = int.from_bytes(byte, byteorder='little', signed=False)
        print(i)
        count += 1
        # this is analogue of 'size=8' in R code
        byte = f.read(4)
        byte = f.read(4)

或者你可以把它作为一个函数。有些参数目前没有使用,请稍后工作:)

^{pr2}$

下面是用法:

i = readBin('bintest.dat', int, n = 4, size = 8, endian = 'little', signed = False)
print(i)
[1, 3, 5, 7]

供您检查的一些链接:

Working with binary data

Reading binary file

相关问题 更多 >