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

No comments:

Post a Comment