C program to SWAP the nibbles of a character | SWAP the nibbles of given character

Spread the love
C program to swap the nibble of the given input. Nibble means 4 bits memory area. So we can use right shift and left shift to swap the nibbles.
/*********** Program ***********/
#include<stdio.h>
void main()
{
char ch;
int i;
printf(“Enter a character : “);
scanf(” %c”,&ch);
printf(“Before Swapping : “);
for(i=7;i>=0;i–)
{
printf(“%d”,((ch>>i)&1 ? 1 : 0));
}
ch = (ch<<4) | (ch>>4);
printf(“nAfter Swapping : “);
for(i=7;i>=0;i–)
{
printf(“%d”,((ch>>i)&1 ? 1 : 0));
}
printf(“n”);
}
/*********** OUTPUT ************/


Here two for loops are printing the binary equivalent of character logic for printing binary equivalent is ((data >> bit)&1).

actual logic is (ch>>4) | (ch<<4), just we are shifting right and left side. 

Venkatesh Macha

Hi Guys, I am Venkatesh Macha. I am a programmer and an Open Source enthusiast, Presently working as a Software Engineer. Apart from that, I love to explore new technologies and things.

You may also like...

Leave a Reply