This blog is under construction

Tuesday 9 July 2013

C program to swap nibble in a byte

Write a 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("Enter your byte 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("Data length less "
                        "than/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", byte);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your byte in binary:11100110
  After swapping the nibbles: 01101110




See Also:

2 comments:

  1. Nice and very helpful C Programming article..... keep posting such a informative articles.....

    ReplyDelete
  2. It is neat blog article. I really admire your effort; keep up the excellent quality writing, it’s rare to see a great blog like this one nowadays. Thanks so much for sharing. lasuth nd orthopedic cast technology admission form

    ReplyDelete