[Tutor] Re: how to separate hexadecimal
kraus at hagen-partner.de
Wed Feb 2 09:12:55 CET 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
Not sure where you get hexa from, but given your example you can use
int(x, base) with base = 16 to convert your string to an integer and
then use the %x formatstring:
>>> hexa = '0x87BE'
>>> upper = int(hexa[2:4], 16)
>>> lower = int(hexa[4:6], 16)
>>> print '0x%x + 0x%x = 0x%x' % (upper, lower, upper+lower)
0x87 + 0xbe = 0x145
More information about the Tutor