Q:

C program to swap two bits of a byte

0

C program 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)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C solved programs/examples on Bitwise Operators

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to get minimum number of bits to store a... >>
<< C program to check whether all bits of a number ar...