×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

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?

Problem statement

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

#include <stdio.h>

/*
Program to swap 1st and 2nd bit of hexadecimal value stored in data variable
*/

int main()
{
    unsigned char data = 0xA; // Assiging hexadecimal value

    // Get 1st bit from data
    unsigned char bit_1 = (data >> 1) & 1;

    // Get 2nd bit from data
    unsigned char bit_2 = (data >> 2) & 1;

    // Get XOR of bit_1 and bit_2
    unsigned char xor_of_bit = bit_1 ^ bit_2;

    printf("After swapping the bits, data value is: %2X", data ^ (xor_of_bit << 1 | xor_of_bit << 2));

    return 0;
}

Output

After swapping the bits, data value is:  C

C Bitwise Operators Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.