Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | Joe Pfeiffer <pfeiffer@cs.nmsu.edu> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: maximum value of int |
| Date | 2011-09-17 10:31 -0600 |
| Organization | A noiseless patient Spider |
| Message-ID | <1blitnjfl8.fsf@pfeifferfamily.net> (permalink) |
| References | <394fc242-c6ae-41ba-9861-6d4c88ec25b5@f17g2000yqh.googlegroups.com> <9dipadFr5dU3@mid.individual.net> <a8a298dc-0fd8-4f6f-834a-880d9b57d917@d12g2000vba.googlegroups.com> |
Stanley Rice <heconghui@gmail.com> writes:
>
> If my assumption is right, then I am confused about the different
> result of the following lines:
> printf("%u\n", (unsigned)-1 >> 1); // 1
> printf("%u\n", (unsigned)(-1 >> 1)); // 2
> printf("%u\n", (unsigned)(-1 >> 2)); // 3
> printf("%u\n", (unsigned)-1); // 4
> The statement 1 prints 2147483647, which is what i want. But statement
> 2, 3, 4 all print the same, 4294967295. That is what I am confused
> about. Why statement 1 and statement 2 generate different results? And
> why statement 2, 3 and 4 generate the same result?
My experience has always been that when experimenting with seeing it
patterns, I'm better off printing them in hexadecimal with a %08x (for a
32 bit system).
Anyway:
The first one is taking a -1, interpreting it as unsigned, and then
right-shifting one bit. Since it's unsigned, it shifts 0s in from the
left, so you get 7fffffff.
The other three are all doing the shift first (well, there is no shift
for the fourth one, but we'll see in a moment that that doesn't
matter). Because you're shifting a negative number, the shift is
shifting copies of the sign bit in. -1 is 0xffffffff; -1 right-shifted
by one (but shifting a 1 in on the left) is still 0xffffffff, and -1
right-shifted by two, but still copying the sign bit in, is still
0xffffffff.
IIRC, this behavior is not guaranteed by the standard.
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
maximum value of int Stanley Rice <heconghui@gmail.com> - 2011-09-16 22:07 -0700
Re: maximum value of int Ian Collins <ian-news@hotmail.com> - 2011-09-17 17:25 +1200
Re: maximum value of int Stanley Rice <heconghui@gmail.com> - 2011-09-17 00:47 -0700
Re: maximum value of int Paul N <gw7rib@aol.com> - 2011-09-17 03:53 -0700
Re: maximum value of int Ben Bacarisse <ben.usenet@bsb.me.uk> - 2011-09-17 12:17 +0100
Re: maximum value of int Joe Pfeiffer <pfeiffer@cs.nmsu.edu> - 2011-09-17 10:31 -0600
Re: maximum value of int Ben Bacarisse <ben.usenet@bsb.me.uk> - 2011-09-17 19:51 +0100
Re: maximum value of int Keith Thompson <kst-u@mib.org> - 2011-09-17 14:39 -0700
Re: maximum value of int Eric Sosman <esosman@ieee-dot-org.invalid> - 2011-09-17 07:51 -0400
csiph-web