Joe Pfeiffer
6/8/2011 6:50:00 PM
Ben Pfaff <blp@cs.stanford.edu> writes:
> Mateusz_madi <madi.czadi@gmail.com> writes:
>
>> if char is 8 bit long so -1 is : 1111 1111
>> and i assign it to int which let's say is 32 bit long, shoudn't int
>> look like: 0000 0000 0000 1111 ?
>
> No. Type conversions in C preserve value, not bit pattern. If
> you assign -1, of any integer type, to an object with any other
> signed integer type, the destination will have value -1.
To amplify (so I'm not disagreeing with Ben here), in general if a
signed value is copied into a larger word, the value of the integer is
preserved if the sign bit is extended across all the new high-order
bits. So, since your sign bit was a 1, all the new bits are 1's as
well. This is called "sign-extending".
> I don't understand how you'd come up with the bit pattern that
> you suggested anyway. You wrote a total of 16 bits (not 32), and
> you only made 4 of them 1-bits (not 8).
I'll guess he meant
0000 0000 0000 0000 0000 0000 1111 1111
Sign-extended, he would actually get
1111 1111 1111 1111 1111 1111 1111 1111
Something else that ought to be noted is that char can be either signed
or unsigned (it's implementation-dependent). If he wants it to be
signed, he should use a signed char.