Subj : Re: possible overflow? To : comp.programming From : CBFalconer Date : Wed Aug 24 2005 10:27 pm Rob Somers wrote: > > 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. > > My machine is a 64 bit Athlon64. Any help appreciated. You are doing shift operations on an integer. This is not portable, as whether or not the sign bit is copied is implementation defined. In general, never do shift operations on integers, only unsigned integers. Try to keep your lines under 72, or better 65, characters. That avoids ugly wrapping when quoted. -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson .