1

I'm trying to port this library from Javascript to Python, but keep getting a strange error in my attempt to convert a hexadecimal string to integer. It works fine for short strings, but for some reason chokes on larger ones:

ValueError: invalid literal for int() with base 16: '14fdbc5ade9e3d4097f421fe7b4b54ad05883d589c3b3f6648b5e0ea2b64b359158087b793b859a4c51af0fd8c1edb7a92b8d5843c1a2d659929357c7e1869784435d6dcfd8d29b619194333b38655493eb4eb3deeffbf339e91c7c0f6113b4bb6672f49'

The code looks like this:

def stretch(value):
    hexadecimal = hex(value)[2:]
    buffer = hexadecimal
    while True:
        buffer += record_separator + hexadecimal
        if len(buffer) >= minimum_digits:
            break
    return int(buffer, 16)
4
  • 2
    If you just want to convert the string to decimal the use value = int(string, 16). Python 3 has no limit on it's integer value. Your string result in 546755182137531943293891170863886409257177002102958031106970218913938945216495276608761007929774380907079475078176395384371438944791022503587328767282546555465705414556027853888426781796298321719051075009856267471199860627126795651319803721 Commented Nov 22, 2020 at 7:05
  • 1
    Okay, so this may just be a compatibility issue then. Invoking 'python --version', I get 'Python 2.7.17'. Commented Nov 22, 2020 at 7:18
  • 1
    Yep, wrong version. Works just fine on Python 3. If you'd like to post that as an answer I'd gladly accept it as solved. And thanks for the timely response. Commented Nov 22, 2020 at 7:27
  • 1
    You're welcome. Posted it as an answer. Commented Nov 22, 2020 at 7:39

1 Answer 1

2

Python 3 has no limit on it's integer values.

So you can use int(hex_string, 16) to convert even large strings to an integer value.

s = '14fdbc5ade9e3d4097f421fe7b4b54ad05883d589c3b3f6648b5e0ea2b64b359158087b793b859a4c51af0fd8c1edb7a92b8d5843c1a2d659929357c7e1869784435d6dcfd8d29b619194333b38655493eb4eb3deeffbf339e91c7c0f6113b4bb6672f49'

s_int = int(s, 16)

print(s_int)

Result

546755182137531943293891170863886409257177002102958031106970218913938945216495276608761007929774380907079475078176395384371438944791022503587328767282546555465705414556027853888426781796298321719051075009856267471199860627126795651319803721
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.