Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

06
Feb

Bit swapping - Style II

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
* Interchange bits of a byte in the following pattern:
* bit7 <-> bit0
* bit6 <-> bit1
* bit5 <-> bit2
* bit4 <-> bit3
*
*/
#include <stdio.h>
#include <stdlib.h>

#define mask(byte, pos) ((byte) & ~(1<<(pos)))
#define get_bit(byte, pos) ((byte) & (1<<(pos)))
#define program_bit(byte, pos, low_high)    \
        byte = mask(byte, pos);             \
        if (low_high)                       \
            byte  = byte | (1<<pos);

int
main (void)
{
    unsigned char byte = 0×0;
    int i, j;
    int bit_i, bit_j;

    printf("byte: %x\n", byte);
    for(i=0, j=7; i<j; i++, j–)
    {
        bit_i = get_bit(byte, i);
        bit_j = get_bit(byte, j);
        program_bit(byte, i, bit_j);
        program_bit(byte, j, bit_i);
    }
    printf("byte: %x\n", byte);

    return EXIT_SUCCESS;
}

Popularity: 14%

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