Subj : Re: possible overflow? To : comp.programming From : jimmaureenrogers@worldnet.att.net Date : Sun Aug 21 2005 09:04 am mr_semantics@hotmail.com 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 > It appears to me that both the answer you are getting and your expected answer are wrong. Each time through your loop you shift I left and J right. There is no combination of shifting, as your program is written, that should output a 1. The following Ada program achieves the correct results: ----------------------------------------------------------------------- -- Binary shifting using shifting ----------------------------------------------------------------------- with Ada.Text_Io; use Ada.Text_Io; with Interfaces; use Interfaces; procedure Binary_Shift2 is I, J : Unsigned_64; Result : Unsigned_64; begin J := Shift_Left(1, (Unsigned_64'Size - 1)); I := 1; while I /= 0 loop Result := I and J; if Result /= 0 then Put('1'); else Put('0'); end if; I := Shift_Left(I, 1); J := Shift_Right(J, 1); end loop; New_Line; end Binary_Shift2; 0000000000000000000000000000000000000000000000000000000000000000 Jim Rogers .