Python program to swap two nibbles in a byte
Hello Everyone! In this tutorial, we are going to swap two nibbles in a byte in Python. First of all, A nibble is a four-bit binary number. for example, 0011,1010,1111 are all nibbles. 1 byte has 8 bits. so. it contains two nibbles. we are going to swap the nibbles in the byte and see how the value changes due to swapping. For this, you don’t need any special packages to install. This looks very simple. First, we will see how to do it by simple builtin functions and then by operators.
Implementation: swap two nibbles in a byte in Python
def nibbles(x): bin_num=bin(x)[2:].zfill(8) print("Enter binary number: ",end='') print(bin_num) new_num=bin_num[4:8]+bin_num[0:4] print("Swapped binary number: ", end='') print(new_num) a=int(new_num,2) print("New Decimal number formed by swapping: ", end='') print(a) nibbles(100)
bin(x) just gives string starting with ‘0b’ following binary number. That’s why I used bin(x)[2:]. ZFILL is used because to fill extra digits with zero. and swapped the nibbles just by string indexing. int(num,2) converts the binary number to decimal number. Let’s see the output
Enter binary number: 01100100 Swapped binary number: 01000110 New Decimal number formed by swapping: 70
yeah, the final output reached. Now, we can see the implementation by operators.
def nibbles(x): print("Last Nibble: ",end='') print(bin(x & 0x0F)[2:].zfill(4)) print("First Nibble: ", end='') print(bin(x & 0xF0)[2:].zfill(4)) a=((x & 0x0F) << 4 | (x & 0xF0) >> 4) print("Swapped bits: ", end='') print(bin(a)[2:].zfill(8)) print("New number: ",end='') print(a) nibbles(100))
simply we have used left shift operator (<<) and right shift operator (>>) to move the bits num&0X0F gives the last nibble and num&0XF0 gives the first nibble.
Last Nibble: 0100 First Nibble: 1100000 Swapped bits: 01000110 New number: 70
We hope that this gives you a better understanding to swap the nibbles in the byte in Python. Thank you.