2

I want to read 4 byte of a binary file until it ends and want to display the result as a hex string e.g.

First 4 Bytes of my file are:

4D 5A 90 00

Result should be:

0x00905A4D

And I also want to be able to do different operations on the result for example:

result = 0x00905A4D
tmp = result & 0xFF

tmp should then be 0x4D

What's the most elegant way for doing this?

2
  • possible duplicate of Python conversion from binary string to hexadecimal Commented May 9, 2015 at 13:57
  • 1
    Also, the syntax for hexadecimal literals is: 0x6789abcd. So in your example you'd want to use result = 0x00905a4d; tmp = result & 0xff. Commented May 9, 2015 at 14:01

1 Answer 1

5

The following code does what you want:

from struct import unpack

inputFile = open("test.txt", "r")
byteString = inputFile.read(4)

# Unpack the first 4 bytes as a little ended unsigned integer
result = unpack("<I", byteString)[0]

# Do some bit arithmetic
tmp = result & 0xff

# Show variable values
print("%08x %08x" % (result, tmp))
Sign up to request clarification or add additional context in comments.

Comments

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.