Featured Post

Trie implementation in C

Reverse a byte's two equal halves

This program reverses a byte's two halves separately

e.g. if the input is 1100 1010

Then the output will be 0011 0101

The last line in the function reverse_half() is explained like this :

*ch = (rev(temp1) << 4) | ((rev(temp2) >> 4) & mask2);

1. *ch returns the resultant reversed bits

2. (rev(temp1) << 4)

Here we first take the reverse of temp1 i.e first four bits of the byte

So suppose if the input byte is 1100 0010 then temp1 would be 1100 0000 and rev(temp1) would be 0000 0011 now since these are first four bits we need to put them back as first four bits .
So we left shift by 4 bits rev(temp1) << 4 , which gives us 0011 0000

Similarly for the latter half of the byte (rev(temp2) >> 4) & mask2 gives 0000 0100

Now we bitwise OR these results i.e. 0011 0000 | 0000 0100 = 0011 0100



#include <stdio.h>
#include <limits.h>

void showbits(unsigned char byte)       // To display bits in a character
{
    unsigned char bit;
    for ( bit = 1 << (CHAR_BIT - 1); bit; bit >>= 1 )
    {
        putchar(byte & bit ? '1' : '0');
    }
    putchar('\n');
}

char rev(char ch)               //This function reverses a character's bit pattern
{
  char rev_char = ch;
  int siz = sizeof(char)*CHAR_BIT -1;
  
  ch = ch >> 1;

  while(ch)
  {
    rev_char = rev_char << 1;
    rev_char = rev_char | (ch & 1);
    ch = ch >> 1 ;
    siz--; 
  }

  rev_char = rev_char << siz;
  
  return rev_char;
}

char reverse_half(char *ch)
{
    char temp1,temp2;
    unsigned char mask1 = 0xf0;  // 11110000
    unsigned char mask2 = 0x0f;  // 00001111

    temp1 = *ch & mask1;        //To get the first four bits
    temp2 = *ch & mask2;        //To get the last four bits

    *ch = (rev(temp1) << 4) | ((rev(temp2) >> 4) & mask2);

}
int main()
{
    char ch;

    printf("\nEnter a byte to reverse it to reverse its two halves: ");
    ch = getchar();   
    getchar();        //To ignore '\n'
    printf("\nYou entered : ");
    showbits(ch);
    reverse_half(&ch);
    printf("\nOutput : ");
    showbits(ch);
}

Comments