# Difference between sign extension and padding

I study computer science and I learn about sign extension. I wonder: Are sign extension and padding referring to the same technique?

Padding is a generic term that means filling up unused space with some pattern. There are a lot of different methods of padding, depending on what exact context it is being used in, for instance in cryptographic uses padding often includes a length field in order to ensure that the original size before padding can be determined.

Sign extending is a method used to convert a signed binary integer of one given size (in twos complement form, which is the most common method of storing such integers) to a larger signed integer. The process is add new bits on the left by duplicating the leftmost bit; i.e. for negative numbers the value is padded with 1s and for positive numbers it is padded with 0s, which will result in the same original value being retained in the new format.

Unsigned integers are increased in size by using "zero extension", which always uses a 0 bit.

This can be seen as padding if you want to view it in terms of using up available space, but really I think "format conversion" is a more natural way of thinking about the operation.

I am assuming a two's complement representation of signed integers.

For example, take an `int8_t{-1}`. It is represented as `1111'1111`, because two's complement can be calculated as (in simple terms):

• take the unsigned representation (`0000'0001`)
• invert all the bits (`1111'1110`)
• add one (`1111'1111`)

Let's sign-extend it to `int16_t`. Then, `1111'1111` becomes `1111'1111'1111'1111`. It is still a `-1` - the value didn't change, only its width did.

Let's pad (with zeroes) it to `int16_t`. Then `1111'1111` becomes `0000'0000'1111'1111`. It is not a `-1` - the value has changed because of the pad.

For unsigned integers there's no difference between sign extension and padding (sing extension does not even make sense, because there is no sign). For signed integers there's a world of difference, though.