3

Using Python 2.7 I had this code:

#Create a random 56 bit (7 byte) string
random_bytes = os.urandom(7)
random_bytes = int.from_bytes(random_bytes, byteorder="big")

Which gives the error:

AttributeError: type object 'int' has no attribute 'from_bytes'

After reading online it looks like from_bytes is Python 3. So I tried the following:

  random_bytes = os.urandom(7)
  #random_bytes = int.from_bytes(random_bytes, byteorder="big")
  random_bytes = struct.unpack('>16B', random_bytes)

But this gives the following error:

struct.error: unpack requires a string argument of length 16

Should the >16B be >7B? Even with that it seems to return a tuple.

The goal is to use random_bytes like this:

int(str(((time_bytes << 56) | random_bytes)) + code)
Prometheus
  • 32,405
  • 54
  • 166
  • 302
  • http://stackoverflow.com/questions/30402743/python-2-7-equivalent-of-built-in-method-int-from-bytes does this help? – timgeb Feb 21 '16 at 18:45
  • @timgeb No I'm sure ``struct.unpack`` is the way to go here – Prometheus Feb 21 '16 at 18:47
  • 1
    You're asking struct to unpack a 7 byte sequence into a tuple of 16, 8 bit integers... – thebjorn Feb 21 '16 at 18:50
  • 1
    Your goal statement doesn't need all those parenthesis or type conversions, it can be written simply as: `time_bytes << 56 | random_bytes + code` (it will be an int, and operator precedence is the same as your parens..) – thebjorn Feb 21 '16 at 18:59

2 Answers2

2

Maybe this will help:

import os

binary = os.urandom(7)
result = int(binary.encode('hex'), 16)
Cosinux
  • 321
  • 1
  • 4
  • 16
1

Maybe this will work for you:

r = chr(0) + os.urandom(7)  # pad with zeroes
struct.unpack('>q', r)

q being the code for signed 8-byte integer (Q is unsigned).

The result is a tuple with one element.

thebjorn
  • 26,297
  • 11
  • 96
  • 138