Bit swapping - Style II
Related Blog Items
- Bit swapping - Style I
- Swapping nodes in a single linked list
- 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
* 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 - Bit swapping - Style I
- Swapping nodes in a single linked list
- 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
- Bit swapping - Style I
- Swapping nodes in a single linked list
- 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.