----- Original Message -----
From: "Prakash"
To: ;
Sent: Tuesday, April 20, 2004 11:23 AM
Subject: [C-Guru] how to swap the LSB and MSBs in a BYTE
>
> Hi,
>
> Can any body tell me(c-program) how to swap the BYTE.
>
> For example: the given byte is: 0101 1101
>
> The output of the program should be: 1011 1010(i.e MSB(0) and LSB(1)
> are swaaped, then again swcond time MSB(1, second bit from MSB) and
> LSB(0, left bit of LSB) swapped.
>
> Thanks,
>
> Newbie
The only way to understand is: trace it.
F:\Vijay\C> type swap_bits.c
/*
* swap_bits.c - Swap corresponding bits
* Author - Vijay Kumar R Zanvar
* Date - Mar 21, 2004
*/
/*
* 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
#include
#include
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 ) << lsb;
bits |= ( (uc & (1<> 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;
}
F:\Vijay\C> gcc swap_bits.c
F:\Vijay\C> a.exe
The byte: 0xef
After bit swapping: 0xf7
               (
geocities.com/vijoeyz/faq)                   (
geocities.com/vijoeyz)