In wikipedia it says what sign extension is but it doesn't say what it's used for or when it is used. I read Hennesy's book "Computer Organization and Design" and it has a sign-extension mechanism mentioned on page 124. As far as I understand the sign entension is used to align numbers that have different length i.e. 16-bit numbers, 24-bits number etc all to same length e.g. 32 bits. But why do these numbers have different length to begin with? Is it because these number can be different data types and therefore have different lengths? For instance, the number can be the 16-bit immediate part of a 32-bit assembly instruction and then the 16-bit number would need sign extension. Is this true?
-
1\$\begingroup\$ Yes, in Hennessy and Patterson's book the typical reason that you need sign extension is because all the data values (in the registers and memory) in the example machines are 32-bits, but the immediate values in the assembly instructions are only 16-bits. You need to extend the immediates to 32 bits so you can add/subtract them from register values (as explained by @David Kessner.) \$\endgroup\$– Wandering LogicCommented May 5, 2013 at 2:00
1 Answer
You sign-extend anytime you need to increase the number of bits in a value. Usually, this is done right before you do mathematical operations on two values. For example, when you add two signed integers, the number of bits in both numbers needs to be identical.
There are many reasons why you might not have the same number of bits in two values. One value might be a 16 bit integer, while another might be a 32 or even 64 bit int. The number doesn't have to be a a multiple of 8 bits either-- there are many analog-to-digital converters that do 10, 12, or 20 bits.