1

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.