0

I'm trying to convert some code using the readBin function (R) into Python.

R code:

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)

Returns:

[1] 1 3 5 7

My attempt in Python:

with open("bintest.dat", "rb") as datfile:
    i = int.from_bytes(datfile.read(8), byteorder='little', signed=False)
    print(i)

Returns:

8589934593

How can I get the same output in Python (I know that I'm missing the n parameter, but I can't find a way to implement it properly).

Thanks

mvacher
  • 23
  • 2

1 Answers1

1

Try this:

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)

Or you can do it as a function. Some parameters are not used at the moment, work for later :)

def readBin(file, fun, n, size, endian, signed):
    with open(file, "rb") as f:
        r = []
        count = 0
        byte = f.read(4)
        while count < n and byte != b"":
            i = int.from_bytes(byte, byteorder=endian, signed=signed)
            r.append(i)
            count += 1
            byte = f.read(4)
            byte = f.read(4)
    return r

And then here will be the usage:

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

Some links for you to examine:

Working with binary data

Reading binary file

Denis Rasulev
  • 3,744
  • 4
  • 33
  • 47