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?

mr.proton
  • 993
  • 2
  • 10
  • 24
  • possible duplicate of [Python conversion from binary string to hexadecimal](http://stackoverflow.com/questions/2072351/python-conversion-from-binary-string-to-hexadecimal) – Tim Biegeleisen May 09 '15 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`. – Phylogenesis May 09 '15 at 14:01

1 Answers1

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))
Phylogenesis
  • 7,775
  • 19
  • 27