If you wanted to get the high and low nibble of a byte. In other words split the 8-bits into 4-bits.
Considering the data string is a string of bytes as hexadecimals, then you could simply do:
high, low = byte[:1], byte[1:2]
print(high, low)
Which for byte = "16"
would print 1 6
. You can then use int(high, 16)
and int(low, 16)
to convert it to decimals.
If you've already converted the hexadecimal into a decimal using int(byte, 16)
then you can extract the high and low nibble by doing:
high, low = byte >> 4, byte & 0x0F
print(hex(high), hex(low))
Which for byte = 0x16
would print 0x1 0x6
because they're converted back to hexadecimals using hex(x)
. Note that hex(x)
adds a 0x
prefix. You can remove it by doing hex(x)[2:]
.
So considering your data string as:
bytes = "10,00,00,00,00,00,16,0A,20,20,20,20,00,00,00,00,00,00,00,00,50"
Then to print each high and low nibble could be done with something like this:
bytes = "10,00,00,00,00,00,16,0A,20,20,20,20,00,00,00,00,00,00,00,00,50"
bytes = bytes.split(",")
for byte in bytes:
byte = int(byte, 16)
high, low = byte >> 4, byte & 0x0F
print(hex(byte), hex(high), hex(low))
Which yields the byte, high nibble and low nibble all in hexadecimals.
Also if you have it in bits ("{0:08b}".format(byte)
) then you can split it like this high, low = bits[:4], bits[4:8]
, now high, low
each having their 4-bits.