Does C sign extend constants or zero extend them? For example:
int a = 123 & 0x3
is the 0x3 zero extend or sign extended? Also in general, what things are zero extended in C and what are sign extended?
Thanks!
C decides whether to sign extend or zero-extend when you cast an integer type based on whether it's signed or unsigned.
Sign extension is used for signed loads of bytes (8 bits using the lb instruction) and halfwords (16 bits using the lh instruction). Sign extension replicates the most significant bit loaded into the remaining bits. Zero extension is used for unsigned loads of bytes ( lbu ) and halfwords ( lhu ).
A similar concept is zero extension (abbreviated as zext). In a move or convert operation, zero extension refers to setting the high bits of the destination to zero, rather than setting them to a copy of the most significant bit of the source.
Sign-magnitude sign extension[edit] Similar to two's complement, in a sign-magnitude representation, the most-significant bit is also used to indicate the sign. Sign extension on sign-magnitude numbers works the same as two's complement.
The C standard does not mandate whether the implementation uses 2's complement, 1's complement, or something else. So the representation of negative values is not mandated either.
However, in your particular case, 0x3
is a positive value, so sign-extension and zero-extension are the same thing!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With