how to separate hexadecimal

Discussion in 'Python' started by jrlen balane, Feb 2, 2005.

  1. jrlen balane

    jrlen balane Guest

    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
     
    jrlen balane, Feb 2, 2005
    #1
    1. Advertising

  2. jrlen balane

    Paul Rubin Guest

    jrlen balane <> writes:
    > 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)
     
    Paul Rubin, Feb 2, 2005
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Dmitry Bond.

    Hexadecimal formatting with leading zeros?!

    Dmitry Bond., Oct 13, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    8,110
    Oliver Sturm
    Oct 13, 2005
  2. Victor Hannak
    Replies:
    0
    Views:
    7,521
    Victor Hannak
    Feb 20, 2004
  3. EvgueniB
    Replies:
    1
    Views:
    671
    Anthony Borla
    Dec 15, 2003
  4. Frank Fredstone
    Replies:
    1
    Views:
    466
    Jean-Francois Briere
    Jun 27, 2006
  5. jrlen balane

    Re: how to separate hexadecimal

    jrlen balane, Feb 2, 2005, in forum: Python
    Replies:
    3
    Views:
    1,278
    Nick Coghlan
    Feb 2, 2005
Loading...

Share This Page