C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C programs » C programs on Bitwise Operators

C program to swap two bits of a byte

Swapping of two bits of a byte using C program: Here, we will learn how to swap two bits of a byte?

Given a byte (an integer number of 8 bits) and we have to swap its any two bits using C program.

In this program, we declared an unsigned char type variable to read 8 bits number (byte) and we are swapping two bits (1 and 2) of given number.

Example:

Input number:  0x0A (Hexadecimal)
Binary of input number: 0000 1010
After swapping of bit 1 and 2
Binary will be: 0000 1100
Output number will be: 0x0C (Hexadecimal)

Swapping two bits of a byte using C program

/*C program to swap two bits of a byte.*/

    #include <stdio.h>

    int main()
    {
	    unsigned char data=0x0A;

	    // swaping 1st bit to 2nd bit (bit counting 7-0).
	    // binary of 0x0A is : 0000 1010

	    data^=(1<<1);
	    data^=(1<<2);

	    // data will be : 0000 1100 (0x0C)
	    printf("\ndata after swap bits : %02X",data);

	    return 0;
    }

Output

data after swap bits : 0C




Sponsored Links




COMMENTS