@dave Nice explanation!

Yanan Cao



On Tue, Aug 21, 2012 at 10:32 AM, Dave <dave_and_da...@juno.com> wrote:

> @Wladimirufc: You responded that the type is int. This data type (usually)
> is 32 bits in length, and stores integers in the twos-complement number
> system. See http://en.wikipedia.org/wiki/Two%27s_complement for an
> explanation of this number system. In this number system, the bits
> (numbered 0 to 31 from the right) have values 2^i (2 to the ith power) for
> i = 0, 1, ..., 30, while bit 31 has value -2^31.
>
> In your code, you set x to have a 1-bit in bit 31 and zeros elsewhere.
> Thus, the value of x is -2^31, which is the value printed by the first
> printf() statement. This value is negative, so the value is negated. In
> twos-complement arithmetic, a value is negated by complementing the value
> (switching 0s to 1s and 1s to 0s) and then adding 1. I.e., the statement x
> = -x is functionally equivalent to x = (~x) + 1. For your value of x, the
> resulting value is the same as the original value, so the second printf()
> statement also prints the value -2^31.
>
> I'm glad you asked this question because it is very important to
> understand how quantities are stored in C and how the arithmetic works.
>
> Dave
>
> On Tuesday, August 21, 2012 11:25:11 AM UTC-5, wladimirufc wrote:
>
>>  Somebody could explain to me why this happen:
>>  x = (1<<31);
>>  printf("%d\n",x);
>>  if(x<0) x = -x;
>>  printf("%d\n",x);
>>
>> Output:
>>
>> -2147483648
>> -2147483648
>>
>> Wladimir Araujo Tavares
>> *Federal University of CearĂ¡ <http://lia.ufc.br/%7Ewladimir/>
>> Homepage <http://lia.ufc.br/%7Ewladimir/> | 
>> Maratona<https://sites.google.com/site/quixadamaratona/>|
>> *
>>
>>
>>
>  --
> You received this message because you are subscribed to the Google Groups
> "Algorithm Geeks" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/algogeeks/-/7a3Wer6PRRQJ.
>
> To post to this group, send email to algogeeks@googlegroups.com.
> To unsubscribe from this group, send email to
> algogeeks+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/algogeeks?hl=en.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algogeeks@googlegroups.com.
To unsubscribe from this group, send email to 
algogeeks+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to