I am trying to write a program in C that prints bits of int. for some reason i get wrong values,
void printBits(unsigned int num){
unsigned int size = si
How about this Macro:
#define print_bits(x) \
do { \
unsigned long long a__ = (x); \
size_t bits__ = sizeof(x) * 8; \
printf(#x ": "); \
while(bits__--) putchar(a__ & (1 << bits__) ? '1' : '0'); \
putchar('\n'); \
} while(0)
Use like:
char c = 3;
int i = -1;
print_bits(c);
print_bits(i);
output:
c: 00000011
i: 11111111111111111111111111111111
If you don't want to print the expression 'x' which is the argument to 'print_bits' remove the line:
printf(#x ": "); \
This Marco can be used on any primitive datatype and the expression 'x' will be evaluated only once. So you should be safe from side effects.