2

I am working on an information security course and have an element of code that I need to understand:

"\x66\x68\xb0\xef". # PORT

My understanding is that this should translate to an integer value > 1024 but Im not sure how to calculate this.

I can see this string contains separated HEX values so tried printing the respective HEX values that are separated by \x and get the following:

>> print (int('66',16))
102
>>> print (int('68',16))
104
>>> print (int('b0',16))
176
>>> print (int('ef',16))
239

Obviously this gives me four separate values, so is not what I need, which is a single integer value.

halfer
  • 19,824
  • 17
  • 99
  • 186
nipy
  • 5,138
  • 5
  • 31
  • 72

2 Answers2

4

struct is your friend. It packs integers into bytes and bytes into integers, if this is a big endian representation, then you should do:

import struct
as_int = struct.unpack('>I', the_str)[0]

And for little endian:

import struct
as_int = struct.unpack('<I', the_str)[0]
MByD
  • 135,866
  • 28
  • 264
  • 277
2

You can unpack to an unsigned int with struct:

>>> import struct   
>>> struct.unpack('I',"\x66\x68\xb0\xef")[0]
4021315686
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139