0

For debugging purposes I use the following definition in my C code:

#define print2binary(n) { unsigned i; for (i = 1 << 31; i > 0; i = i / 2) { (n & i)? printf("1") : printf("0"); } printf("\n"); }

It works just fine.

Now I want to be able to print larger values like unsigned long. Therefore I tried the following:

#define print2binary(n) { unsigned long i; for (i = 1 << 63; i > 0; i = i / 2) { (n & i)? printf("1") : printf("0"); } printf("\n"); }

But this definition does not work. I do not see why it should not work. Where is my error in reasoning?

Gilfoyle
  • 3,282
  • 3
  • 47
  • 83
  • 1
    Never use a macro where a function (probably `inline`) will do! And `long` is not necessarily larger than `int` (or `short` or `char`). And your code invokes undefined behaviour for `int` widths < 33 bits, res. 65 bits. If you need defined values, use fixed width types, and read about the pitfalls shifting integers, especially signed integers. – too honest for this site Nov 17 '16 at 22:42
  • You assume that `unsigned long` is 64 bits. You should probably check that assumption. Perhaps you meant `unsigned long long i;` – user3386109 Nov 17 '16 at 22:49
  • To print the binary of _any object_, code may use this [compound literal](http://stackoverflow.com/a/35367414/2410359) approach. – chux - Reinstate Monica Nov 17 '16 at 23:43

0 Answers0