how to separate hexadecimal

Nick Coghlan ncoghlan at iinet.net.au
Wed Feb 2 02:36:04 EST 2005


jrlen balane wrote:
> i have a 4 digit hex number (2 bytes) and i want to separate it into 2
> digit hex (1 byte each) meaning i want to get the upper byte and the
> lower byte since i am going to add this two.
> how am i going to do this?
> should i treat it just like a normal string?
> please help, thanks.
> 
> ex. hexa = '0x87BE"  # what i want to do is:
>       a = 0x87, b = 0xBE    # so that i could do this:
>       c = a + b            #which should be equal to 0x145

divmod does what you want:

Py> val = 0x87be
Py> hi, lo = divmod(val, 0x100)
Py> hex(hi), hex(lo)
('0x87', '0xbe')
Py> hex(hi + lo)
'0x145'

Cheers,
Nick.


-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list