简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM