Header Ads

WAP to Swap Nibbles in a byte in C - 45

This Program Swaps the Nibble from a Byte in C

Program Code:

/* C program to Swap Nibbles in a byte. */ 

#include <stdio.h>
#include <string.h>

int main() 
{
        char byte[10];
        int i = 0, ch;

        /* get 8 byte binary input from the user */
        printf("\n Enter a Number (In Binary) : ");
        fgets(byte, 10, stdin);
        byte[strlen(byte) - 1] = '\0';

        /* if data length is not 8 char long, show error msg */
        if (strlen(byte) != 8) {
                printf(" Error: Number Length is less/greater than 8 Bits! \n");
                return 0;
        }

        /* swapping nibbles in the byte */
        while(i < 4) 
 {
                ch = byte[i];
                byte[i] = byte[i + 4];
                byte[i + 4] = ch;
                i++;
        }

        /* print the result */
        printf(" After Swapping the Nibbles : %s\n\n", byte);
 return 0;
}

Program Output:

No comments