goodvibration
goodvibration

Reputation: 6206

Convert either a hex string or a bytearray into an integer

Given an input which is either a hexadecimal string or a bytearray, I need to convert it into an integer.

Of course, one way to do it is to check on the type, for example:

a = '0xb8c2659029395bdf'
b = bytearray([0xb8,0xc2,0x65,0x90,0x29,0x39,0x5b,0xdf])

def func(x):
    if type(x) == str:
        return int(x,16)
    else:
        return int('0x'+''.join(['{:02x}'.format(i) for i in x]),16)

print(func(a))
print(func(b))

But I'm looking for a "neater" way.

One idea that I had in mind is to start by converting the input into one of the types.

For example:

def func(x):
    return int(str(x),16)

Or:

def func(x):
    return int('0x'+''.join(['{:02x}'.format(i) for i in bytearray(x)]),16)

But for the 1st option I get TypeError: string argument without an encoding.

And for the 2nd option I get ValueError: invalid literal for int() with base 16.

Any idea how to resolve this issue, or to solve the original problem in a different manner?

Upvotes: 0

Views: 81

Answers (2)

Dunes
Dunes

Reputation: 40713

"Neater" isn't always better. It's a waste to turn a bytearray into a string only to then turn the string into an integer, when you can directly turn a bytearray into an integer.

eg.

def func(x):
    if isinstance(x, str):
        return int(x, base=16)
    else:
        assert isinstance(x, (bytearray, bytes))
        return int.from_bytes(x, byteorder='big')

assert func(bytearray(b'\xff\x00')) == func('0xff00') == 0xff00

Upvotes: 1

kalehmann
kalehmann

Reputation: 5011

You can use the hex method of the bytearray to convert the bytearray to a string that you can parse:

def func(x):
    if hasattr(x, 'hex')
        x = x.hex()
    return int(x,16)

For example:

>>> func('0xffff')
65535
>>> func(bytearray([0xff, 0xff])) 
65535

Upvotes: 0

Related Questions