Bit swapping - Style I
Related Blog Items
- Swapping nodes in a single linked list
- Bit swapping - Style II
- What do I need to know when mixing C and C++ code?
- Swapping variables without additional space
- Sorting A Linked List with Bubble Sort
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: 16%
You need to log on to convert this article into PDF
Related Blog Items - Swapping nodes in a single linked list
- Bit swapping - Style II
- What do I need to know when mixing C and C++ code?
- Swapping variables without additional space
- Sorting A Linked List with Bubble Sort
Related Blog Items
- Swapping nodes in a single linked list
- Bit swapping - Style II
- What do I need to know when mixing C and C++ code?
- Swapping variables without additional space
- Sorting A Linked List with Bubble Sort
No Comments
No comments yet.