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):
    print("Enter binary number: ",end='')
    print("Swapped binary number: ", end='')
    print("New Decimal number formed by swapping: ", end='')

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("New number: ",end='')

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.

Leave a Reply

Your email address will not be published. Required fields are marked *