Optical Carrier
Optical Carrier

Reputation: 368

"invalid literal" from int(base64.urlsafe_b64decode(mystr))

I have a base64 string that I need to decode, then i convert it into a integer so I can "% 2" it. the base64 decode is easy but apparently I have some confusion on how python actually handles binary:

>>> y = 'EFbSUq0g7qvoW2ehykfSveb_pSmunxOJUEVao1RWwck'
>>> int(base64.urlsafe_b64decode('EFbSUq0g7qvoW2ehykfSveb_pSmunxOJUEVao1RWwck='), 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: b'\x10V\xd2R\xad \xee\xab\xe8[g\xa1\xcaG\xd2\xbd\xe6\xff\xa5)\xae\x9f\x13\x89PEZ\xa3TV\xc1\xc9'
>>> int(base64.urlsafe_b64decode('EFbSUq0g7qvoW2ehykfSveb_pSmunxOJUEVao1RWwck='), 16)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 16: b'\x10V\xd2R\xad \xee\xab\xe8[g\xa1\xcaG\xd2\xbd\xe6\xff\xa5)\xae\x9f\x13\x89PEZ\xa3TV\xc1\xc9'
>>>

Upvotes: 3

Views: 250

Answers (1)

Poojan
Poojan

Reputation: 3519

Use int.from_bytes() to convert a base64 decoded string into int

int.from_bytes(
    base64.urlsafe_b64decode(
        'EFbSUq0g7qvoW2ehykfSveb_pSmunxOJUEVao1RWwck='
    ),
    'big' # the endianness
)
7390406020584230016520446236832857473226268177813448430255309703833393217993

Upvotes: 3

Related Questions