Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convert hex string to int and back

My python script gets and sends words over a serial line. Each word is a signed 24-bit value, received as hex string. The script should now take these strings and convert them to integers, do some calculations on it, and send them back in the same format. My problem is, how to do this conversion

Examples

Rx string -> calc int
 012345   ->  74565
 fedcba   -> -74566

calc int -> Tx string
  74565  -> 012345
 -74566  -> fedcba

How can this be done?

like image 976
guo Avatar asked Feb 03 '26 04:02

guo


1 Answers

def str_to_int(s):
    i = int(s, 16)
    if i >= 2**23:
        i -= 2**24
    return i

def int_to_str(i):
    return '%06x'%((i+2**24)%2**24)

Test results:

In [36]: str_to_int('012345')
Out[36]: 74565

In [37]: str_to_int('fedcba')
Out[37]: -74566

In [38]: int_to_str(74565)
Out[38]: '012345'

In [39]: int_to_str(-74566)
Out[39]: 'fedcba'

Reference: Hex string to signed int in Python 3.2?

like image 69
Robᵩ Avatar answered Feb 04 '26 17:02

Robᵩ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!