how to separate hexadecimal

J

jrlen balane

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
 
P

Paul Rubin

jrlen balane said:
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

Assuming you really want hexa to begin with the characters '0x', the
string slicing way is:

a, b = hexa[2:4], hexa[4:6] # a = '87', b = 'BE'
c = int(a,16) + int(b, 16)

A more direct arithmetic way is:

x = int(hexa, 16) # x = the integer 0x87be
c = (x >> 8) + (x & 0xff)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,888
Messages
2,569,964
Members
46,293
Latest member
BonnieHamb

Latest Threads

Top