Subj : Re: possible overflow? To : comp.programming From : Rob Somers Date : Thu Aug 25 2005 10:07 pm Peter Shaggy Haywood wrote: > 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.) > Ah, thank you all for your input - I will study it this weekend, and if I have any questions, I will post back. My apologies also for the double post - my service provider was not giving me decent news service on the weekend, and I mistakenly posted twice. Rob Somers .