• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 205
  • Last Modified:

6 Byte Data to Integer

Hi,
I have a 6-bytes of data 01 32 B0 99 A3 2A that I need to convert into a number value.

Using an unpack it only accepts either 4-bytes or 8-bytes for a number.

I need to convert 01 32 B0 99 A3 2A so i get 1317222851370

Thanks
0
yoeddy
Asked:
yoeddy
  • 4
1 Solution
 
farzanjCommented:
Try this
>>> a= '01 32 B0 99 A3 2A'
>>> int(a.replace(" ", ""),16)
1317222851370
0
 
gelonidaCommented:
Depending on the endianness you can prepend or append two zero bytes and then do your unpack.

0
 
gelonidaCommented:
A small example for little endian
TWO_ZERO = '\x00\x00' # constant to prepend / append

istr = 'ABCDEF'  # string to decode

val = struct.unpack('q',istr+ TWO_ZERO)
print '%012x' % val

Open in new window

0
 
gelonidaCommented:
I am confused.

Did you want to convert six bytes or did you want to convert a string with 12 hex digits and some spaces?

My first example was for little endian.
It seems you were looking for big endian above the corrected example.


TWO_ZERO = '\x00\x00' # constant to prepend / append

istr = ='\x01\x32\xB0\x99\xA3\x2A'  # string of 6 bytes

val = struct.unpack('>q', TWO_ZERO + istr)
print val

Open in new window

0
 
gelonidaCommented:
converting arbitrary length strings into a big endian integer could be done with attached code
(though there might be more efficient solutions)

Please note, that I made a typo in my previous post. (line 3 has one '=' character too much)


istr = '\x01\x32\xB0\x99\xA3\x2A' # or string of any other length
int(''.join([ '%02x' % ord(v) for v in istr ]), 16)

Open in new window

0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now