Search code examples
pythonarraysbytenibble

Trying to split byte in a byte array into two nibbles


I am given a byte array and i am trying to test if the first 4 bits of the first byte is equal to 4. If not return the error code 2.

I have tried pulling out the byte from the array and splitting the hexadecimal value fo it but i am not quite sure how to do so as I am new to working with bytes.

def basicpacketcheck (pkt):
    version, hdrlen = bytes(pkt[0:1])
    if version != 4:
        return 2

So here my code

pkt[0:1]

gives me

bytearray(b'E')

and I need to separate​ E (which translates to 0x45) into 0x4 and 0x5.


Solution

  • Use pkt[0] to get the first byte as an int 69. Then, you can use bit-wise shift (<<, >>) and bit-wise and (&) operators against the int object, to split into nibbles:

    >>> pkt = bytearray(b'EAB82348...')
    >>> b = pkt[0]  # 69 == 0x45
    >>> (b >> 4) & 0xf  # 0x45 -> 0x4 -> 0x4
    4
    >>> (b) & 0xf  # 0x45 -> 0x5
    5