Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C sign extend or zero extend constants?

Tags:

c

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!

like image 445
Andrew Avatar asked Jul 10 '11 16:07

Andrew


People also ask

Does C sign extend?

C decides whether to sign extend or zero-extend when you cast an integer type based on whether it's signed or unsigned.

When to sign extend vs zero extend?

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 ).

What does zero extend mean?

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.

Does sign extension work for sign and magnitude?

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.


1 Answers

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!

like image 71
Oliver Charlesworth Avatar answered Oct 05 '22 22:10

Oliver Charlesworth