Subj : Re: possible overflow? To : comp.programming From : Shaggy Date : Fri Aug 26 2005 01:19 am Groovy hepcat mr_semantics@hotmail.com was jivin' on 21 Aug 2005 05:08:49 -0700 in comp.programming. possible overflow?'s a cool scene! Dig it! >I am still fiddling with bitwise operations - this time I have been >working >on a program that accepts input (an unsigned integral) from the user, >and >then after some 'conversion' outputs that number in binary format. I >have >one problem that is vexing me though: > >#include #include >int main(void) >{ > unsigned int input = 8; > unsigned long int i; > unsigned long int j = 0; size_t number_of_bits = sizeof j * CHAR_BIT; j = (1UL << (number_of_bits - 1)); > for (i = 1; i != 0; i <<= 1) { > if (input & j) { > (void) putchar('1'); > } else { > (void) putchar('0'); > } > j >>= 1; > } > puts(""); > return 0; >} I must say that your code goes to unnecessary lengths to do simple things. There's no need for so much complexity. As someone else already pointed out, you can replace the shifting of i with a simple count. Also, it's best to avoid "magic numbers" in code, especially when they introduce an implementation dependance. The number of bits in a byte is not universally 8. The standard C macro CHAR_BIT, defined in limits.h, returns the (implementation defined) number of bits in a byte. You must also realise that there may be non-value bits, even trap bits, in any integral type other than the character types. This makes your code inherently non-portable. But if you can live with excluding those implementations that have non-value bits in their integral types, then that's OK. (Yes, I am being quite anal here. It's for a reason: to teach you better programming habbits. Correctness and portability are key.) -- Dig the even newer still, yet more improved, sig! http://alphalink.com.au/~phaywood/ "Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker. I know it's not "technically correct" English; but since when was rock & roll "technically correct"? .