drdot
drdot

Reputation: 3347

(python) How to convert long into raw string?

I have a piece of code that can do integer to raw string conversion, but it does not take long. Any solutions?

def intToBytes(integer):
  hex_form = hex(integer)[2:]; # 2: gets rid of leading 0x
  if (len(hex_form) % 2):
    hex_form = '0' + hex_form;
  return bytearray.fromhex(hex_form)

Upvotes: 0

Views: 652

Answers (1)

6502
6502

Reputation: 114511

You can just remove the ending 'L' when present:

def intToBytes(integer):
    hex_form = hex(integer)[2:]; # 2: gets rid of leading 0x
    if hex_form[-1:] == 'L':
        # Remove final `L` from arbitrary precision integers
        hex_form = hex_form[:-1]
    if (len(hex_form) % 2):
        hex_form = '0' + hex_form;
    return bytearray.fromhex(hex_form)

Upvotes: 2

Related Questions