Let's take the example of sign-extending a 16-bit signed number into a 32-bit register, such as mov $+/-5, %ax
movswl %ax, %ebx
.
There are two possible cases:
High bit is zero (number is positive). This is very easy to understand and intuitive. For example, if I have the number
5
, left-padding with zeros is very easy to understand. For example:00000000 00000101 # 5 (represented in 16 bits) 00000000 00000000 00000000 00000101 # 5 (represented in 32 bits)
However, the tricky thing for me to understand is when it's a negative number and we sign-extend. Example:
11111111 11111011 # -5 (represented in 16 bits) 11111111 11111111 11111111 11111011 # -5 (represented in 32 bits)
Yes, I know that we just fill the upper bits with 1
. But what makes that work? Perhaps sort of an explanation on what 'properties' of the binary number makes that possible would help me better understand this.