Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

06
Feb

Bit swapping - Style I

Related Blog Items

This program shows a logic of swapping the most significant bit with the least significant bit, second most significant bit with the second least significant bit, and so on.

/*
* swap_bits.c  -   Swap corresponding bits
*/

/*
*  This program swaps the corresponding bits of a character.  For example,
*          msb (bit 7) is exchanged with lsb (bit 0);
*          msb-1 (bit 6) is exchanged with lsb+a (bit 1), so on
*/

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

unsigned char
swap_bits ( unsigned char uc )
{
    unsigned char bits = 0;
    int times = CHAR_BIT / 2,
          msb = CHAR_BIT-1,
          lsb = 0;

     while ( times– )
     {
        bits |= ( (uc & (1<<msb)) >> msb ) << lsb;
        bits |= ( (uc & (1<<lsb)) >> lsb ) << msb;
        msb–;
        lsb++;
     }
         
    return bits;
}

int
main ( void )
{
    unsigned char uc = 0xef;

    printf ( "The byte: %#x\n", uc );
    printf ( "After bit swapping: %#x\n", swap_bits ( uc ) );
    return EXIT_SUCCESS;
}


Popularity: 13%

You need to log on to convert this article into PDF


Related Blog Items

No Comments

No comments yet.

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image