Vtd wrote:
Hi All,
Simple question regarding byte to integer conversion:
integers are 32, char is 8 bits.
unsigned int a;
int b;
char c;
...
a = (unsigned int)c; /* c is 0 extended to integer (upper 24 bits of a
filled with 0's). Correct? */
It depends on the value of `c'.
If `c' is non-negative (which will always be the case if
the implementation uses an unsigned `char'), converting this
non-negative value to `unsigned' will produce a small result
with a lot of high-order zero bits. If `c' is negative (which
can only happen if the implementation uses a signed `char'),
converting this negative value to `unsigned' will produce a
large result with a lot of high-order one bits.
Note that the cast has no effect; `a = c' would behave
exactly the same way.
b = (int)c; /* c is sign extended to integer (upper 24 bits of b are
filled with 1's or 0's depending on bit 7 of c). Correct? */
`b' will be set to the same numerical value as `c', which
will always be non-negative on an implementation with unsigned
`char' and could be either negative or non-negative on an
implementation with signed `char'.
Once again, the cast has no effect; `b = c' would behave
exactly the same way.
I imagine your next question might be "Well then, how do
I zero- or sign-extend a `char'?" The pedantic answer is
"It's difficult," but the practical answer is "It's easy:"
a = (unsigned char)c;
b = (signed char)c;
The analysis for systems that use two's complement for
negative `signed char' values is easy; I'll leave it to you.
The pedant's quibble arises because ones' complement and
signed-magnitude representations are also allowed, and these
make things tricker. It's strange to refer to the first line
above as "zero-extending" in a case where `(unsigned char)c'
may have a different bit pattern than plain `c'. The second
line is even more problematic: if `char' is unsigned and the
value of `c' is too large for a `signed char', the conversion
produces undefined behavior. However, such systems seem to
be quite rare nowadays -- hence the practical "It's easy."
--
Er*********@sun.com