Thursday, March 12, 2015

Swapping bits of an Integer

Swapping individual bits is implemented using a function. This function is repeatedly called with different position data.
typedef unsigned int uint;
uint swapBits(uint x, uint i, uint j) {
uint lo = ((x >> i) & 1);
uint hi = ((x >> j) & 1);
if (lo ^ hi) {
x ^= ((1U << i) | (1U << j));
}
return x;
}
uint reverseXor(uint x) {
uint n = sizeof(x) * 8;
for (uint i = 0; i < n/2; i++) {
x = swapBits(x, i, n-i-1);
}
return x;
}
view raw SwapBits.c hosted with ❤ by GitHub

Wednesday, March 11, 2015

Printing the binary format of a integer

Here printing iss done thru a neat macro trick. We can calculate different way too, which is commonly seen. In that case we divide the number by 2 and not the modulo and append it to a string. Same time we will divide the number by two and make it as the new number. This process continues till the number becomes equivalent to one.
/*
* printbinary.c
*
* Created on: Mar 11, 2015
* Author: prasadnair
*/
/*
* printBinary.cpp
*
* Created on: Mar 11, 2015
* Author: prasadnair
*/
#include <stdio.h>
#define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d"
#define BYTETOBINARY(byte) \
(byte & 0x80 ? 1 : 0), \
(byte & 0x40 ? 1 : 0), \
(byte & 0x20 ? 1 : 0), \
(byte & 0x10 ? 1 : 0), \
(byte & 0x08 ? 1 : 0), \
(byte & 0x04 ? 1 : 0), \
(byte & 0x02 ? 1 : 0), \
(byte & 0x01 ? 1 : 0)
int main()
{
printf("Leading text "BYTETOBINARYPATTERN, BYTETOBINARY(32));
return 0;
}
view raw printbinary.cpp hosted with ❤ by GitHub