×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to swap two nibbles of a byte.

This program will swap two nibbles of a byte, as we know that one byte has 8 bits or 2 nibbles. Hence one nibble has 4 bits, by shifting 4, 4 bits we can swap nibbles of a byte.

Swapping nibbles of a byte using C program

/*C program to swap two nibbles of a given byte*/

#include <stdio.h>

/* function : swapTwoNibbles, to swap two nibbles of a given byte.*/
unsigned char swapTwoNibbles(unsigned char n)
{
    unsigned char num;
    num = ((n & 0x0F) << 4 | (n & 0xF0) >> 4);
    return num;
}

int main()
{
    unsigned char number;
    unsigned char revNumber;
    printf("Enter an integer number (One byte number):");
    scanf("%u", &number);

    revNumber = swapTwoNibbles(number);
    printf("\nEntered Number was : %u \nNumber after swapping nibbles : %u", number, revNumber);

    return 0;
}

Output

Enter an integer number (One byte number):200

Entered Number was : 200
Number after swapping nibbles : 140

C Bitwise Operators Programs »

Related Programs

Comments and Discussions!

Load comments ↻





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