How is sign extension used in practice

computer-architecturecomputers

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?

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