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





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.