简体   繁体   中英

Python 3 : Unexpected ValueError when converting hex to int

When I try to convert a string to bits, it doesn't always work, depending on completely esoteric conditions :

print( int('deadbeef', 16) )
>>> 3735928559

print( int('dead beef', 16) )
ValueError: invalid literal for int() with base 16: 'dead beef'

print( int('hello wolrd', 16) )
ValueError: invalid literal for int() with base 16: 'hello world'

print( int('helloworld', 16) )
ValueError: invalid literal for int() with base 16: 'helloworld'

First it seemed like it just wouldn't work with strings containing spaces, but it actually doesn't work either with "helloworld" or anything the like. Then why would it ever work with "deadbeef" ? I am completely lost oo

If you want to convert a string to a hex representation of its bits, that's not what int(s, 16) does. int(s, 16) tries to treat the characters of s as the base-16 representation of an integer. 'deadbeef' contains only characters that are valid digits in base 16:

d = 13
e = 14
a = 10
d = 13
b = 11
e = 14
e = 14
f = 15

deadbeef = 13*16**7 + 14*16**6 + 10*16**5 + 13*16**4 + 11*16**3 + 14*16**2 + 14*16**1 + 15
         = 3735928559

None of your other strings have that property.

If you want hex digits corresponding to the bits representing a string, first, choose an encoding (UTF8, probably), then use something like binascii.hexlify :

>>> import binascii
>>> binascii.hexlify('hello world'.encode('utf8'))
b'68656c6c6f20776f726c64'

int( hex_value,16) is used to convert hex string to int. You are facing an error if you pass a invalid hex character. For your use case of converting string to bits you can use bitarray module

import bitarray
ba = bitarray.bitarray()
ba.frombytes('Hi'.encode('utf-8'))
print ba

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM