Subj : Re: possible overflow? To : comp.programming From : Roger Willcocks Date : Sun Aug 21 2005 07:09 pm wrote in message news:1124626129.497709.106800@g49g2000cwa.googlegroups.com... >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 > > int main(void) > { > unsigned int input = 8; > unsigned long int i; > unsigned long int j = 0; > size_t number_of_bits = sizeof(j) * 8; > > > j = (1 << (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; > } > > That is a working program that gives an example of my problem - its > output > is: > > 0000000000000000000000000000111111111111111111111111111111111000 > > instead of: > > 0000000000000000000000000000000000000000000000000000000000001000 > > If I declare i and j as unsigned char, short or int, I get results as I > would expect, output of 8, 16, or 32 bits respectively. But long is > not > working. I have sent it through the debugger, to no avail. I am > stumped. Since you're looking at underlying bit patterns, it doesn't really matter whether the variables are signed or unsigned: #include int main(int argc, char* argv[]) { int i; long long foo = 0x123456; for (i = 0; i < 8 * sizeof(foo); i++, foo += foo) putchar('0' + (foo < 0)); return 0; } -- :-) Roger .