3

I'm pretty new to hexadecimal in general, and I've got an application that needs me to split a hexadecimal number. For example, given the number 0x607F, I would need to return the high (0x60) or low (0x7F) byte.

This is may implementation, it feels a little cloogy though. Is there a more standard way to do this in python?

def byte(integer,highlow):
    assert highlow=='high' or highlow=='low'
    if highlow=='high':
        return hex(int(bin(integer)[:-8],2))
    if highlow=='low':
        return hex(int(bin(integer)[-8:],2))
martineau
  • 119,623
  • 25
  • 170
  • 301
Chris
  • 9,603
  • 15
  • 46
  • 67

3 Answers3

15

This returns the high byte and the low byte as a tuple:

def bytes(integer):
    return divmod(integer, 0x100)

For example:

>>> high, low = bytes(0x607F)
>>> hex(high)
'0x60'
>>> hex(low)
'0x7f'

BTW, depending on what you need the bytes for, and where the integer came from, there might be much better ways to do what you need.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • Just barely eeked out unutbu's answer on my machine... 1.8us vs 2.22us. FWIW my code was coming in at 4.97us and only calculating just one. – Chris Feb 23 '13 at 03:26
6
def bytes(num):
    return hex(num >> 8), hex(num & 0xFF)

bytes(0x607F)

yields

('0x60', '0x7f')
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
2

To add to Ned's answer which is quite correct, struct is a powerful tool for extracting bytes.

>>> import struct
>>> print("0x%2x 0x%2x\n" % tuple(struct.pack('<H',0x4355)))
0x55 0x43

In this example, the "<" tells pack to interpret the input as little-endian, and the "H" says to expect a 2-byte number. Struct produces a bytes object (on Python 3), which can then be converted to a tuple to satisfy the string formatting parameters for %x to print out the hex.

Python 2.7 is slightly more cumbersome, only because struct.pack puts the info in a string which must be split into its characters:

>>> print("0x%2x 0x%2x\n" % tuple([ ord(x) for x in struct.pack('<H',0x4355)]))
0x55 0x43

If you really are doing something as simple as this example, it's probably overkill. If you're manipulating more values or different lengths of numbers from, for example, registers observed from a microcontroller, or exchanging data with C or C++, consider using struct to make it easier to wrangle the bytes.

Community
  • 1
  • 1