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,471
  • 17
  • 87
  • 173
nipy
  • 4,326
  • 4
  • 22
  • 53

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
  • 133,244
  • 25
  • 260
  • 270
2

You can unpack to an unsigned int with struct:

>>> import struct   
>>> struct.unpack('I',"\x66\x68\xb0\xef")[0]
4021315686
Moses Koledoye
  • 74,909
  • 8
  • 119
  • 129