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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks but unfortunately this doesn't work. It returns 1 2 3 4 5 6 7 8 9 10
Ok, I've updated the solution. Now it works exactly as your R code.
int.from_bytes does not work in python 2.x. Would one need to use struct?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.