Reputation: 41
I have some files they look like this with hex/octal dump:
hexdump file:
0000000 0002 0000 0c3e 0000 0ac5 0000
000000c
od file:
0000000 000002 000000 006076 000000 005305 000000
0000014
I dont know really what this "000002" and "0000014" is good for but, I know I need this "006076" and "005305" as interger value, so I did this in python2:
hex(006076)
'0xc3e'
int(0xc3e)
3134
I don't know really how I should open/and read this file/values in python2...
simple open/read the file looks like this:
x = open("file", "rb")
x.read()
'\x02\x00\x00\x00>\x0c\x00\x00\xc5\n\x00\x00'
Upvotes: 1
Views: 1250
Reputation: 66
The functions hex(int)
and oct(int)
take an integer in base 10 (decimal) and convert it into a string that looks like a number in base 8 or base 16 (hex or octal). The function int()
just takes a string that looks like a number and converts it from a string into an integer in base 10.
You should be able to use the int()
function to do this with the format int([string representing number], [base of number])
. Here's how it works:
In a base n number system, the value of the number is (1st digit) * n^0 + (2nd digit) * n^1 + (3rd digit) ^ n^2 + ...
. For example, if you have the number 472 in octal (base 8), you could calculate the value like so:
2 * 8^0 + 7 * 8^1 + 4 * 8^2
2 * (1) + 7 * (8) + 4 * (64)
2 + 56 + 256
314
So 472 in octal is equivalent to 314 in decimal. To make a function out of this, I'd do something like this:
def convertToDecimal(number, baseOfNumber):
counter = 0
for c in reversed(number)
newNumber += (c * (baseOfNumber ^ counter))
counter += 1
return newNumber
Hope this helps!
Upvotes: 0
Reputation: 531165
You want to use struct.unpack
.
>>> import struct
>>> struct.unpack("4x H 2x H 2x", '\x02\x00\x00\x00>\x0c\x00\x00\xc5\n\x00\x00')
(3134, 2757)
The format string used as the first argument tells unpack
to ignore the first 4 bytes, then unpack the next two bytes as an integer, ignore 2 more bytes, unpack another 2-byte integer, and ignore the last 2 bytes. This assumes the byte string uses the same endianness as your machine's default; see the documentation for the struct
module for more details.
Upvotes: 3