Section 4.19

Truncation and extension

Definition

Truncation and extension are the two ways to change the number of bits that hold an integer. Truncation, or narrowing, keeps the low-order bits and discards the rest. Extension, or widening, adds high-order bits. Zero extension fills them with 0, which keeps the value of the bits read as an unsigned number. Sign extension fills them with copies of the old top bit, the sign bit, which keeps the value of the bits read as a signed number in two’s complement, the usual encoding of negative integers.

The idea

A sensor message carries a temperature as one signed byte, and the byte 0xFE means −2-2 degrees. The receiving program loads the byte into a 32-bit register. If the load fills the 24 new bits with zeros, the register holds 254, and the program reports 254 degrees; the load must instead copy the byte’s top bit, a 1, into the new bits, which gives the 32-bit pattern for −2-2. A length byte 0xFE, by contrast, means 254 bytes, and copying its top bit would turn it into −2-2, an enormous length once converted to an unsigned size. Which extension is right depends on what the bits mean, and the bits themselves do not say.

Truncation loses information in the opposite direction. A program writes a 32-bit count of 70,000 into a 16-bit field. The field keeps the low 16 bits, which hold 70,000−65,536=4,46470{,}000 - 65{,}536 = 4{,}464. Any check made on the 16-bit field afterwards sees a harmless 4,464.

The intuition for sign extension comes from the weights of the bits. In two’s complement the top bit of a ww-bit number carries the negative weight −2w−1-2^{w-1}. Widening turns that bit into an ordinary bit with the positive weight +2w−1+2^{w-1}, which raises the total by 2w2^w when the bit is 1. Filling the new bits with 1s adds weights that sum to exactly −2w-2^w, because the new top bit counts negatively, so the total is unchanged. When the sign bit is 0 nothing changes, and 0s are the right fill.

How it works

Number the bits of a ww-bit pattern from 0, the lowest, to w−1w - 1, the highest, and let bib_i be bit ii. Read as unsigned, the pattern has the value b0⋅20+b1⋅21+…+bw−1⋅2w−1b_0 \cdot 2^0 + b_1 \cdot 2^1 + \dots + b_{w-1} \cdot 2^{w-1}. Read as two’s complement, it has the same value except that bit w−1w - 1 counts −2w−1-2^{w-1} instead of +2w−1+2^{w-1}. Going from ww bits to vv bits:

When the top bit bw−1b_{w-1} is 0, the two extensions give the same pattern.

Processors provide each operation as an instruction or as part of a load. Arm has LDRB (load a byte and zero-extend it) and LDRSB (load a byte and sign-extend it), and UXTB and SXTB for a byte already in a register; x86 has MOVZX and MOVSX; RISC-V, an open instruction set architecture §4.38 whose name refers to RISC (reduced instruction set computer), has LBU and LB. Instruction sets also differ in what a 32-bit operation does to a 64-bit register: x86-64 and 64-bit Arm zero-extend the 32-bit result, 64-bit RISC-V sign-extends it in instructions such as ADDW, and eBPF §2.1 (extended Berkeley Packet Filter), a 64-bit instruction set for small programs run inside operating system kernels and other hosts, zeroes the upper 32 bits. An interpreter §2.13 or translator for one instruction set must reproduce that set’s rule exactly.

In C, the compiler chooses the operation from the types, following the conversion rules of C11, the 2011 edition of the ISO standard that defines the C language, section 6.3.1.3 (see the Integer promotion and conversion §4.18 entry):

Worked example

Take the 8-bit pattern 11111110, written 0xFE in hexadecimal. Read as unsigned it is 128+64+32+16+8+4+2=254128 + 64 + 32 + 16 + 8 + 4 + 2 = 254. Read as two’s complement, bit 7 counts −128-128 instead of +128+128, so it is −128+126=−2-128 + 126 = -2.

Zero extension to 32 bits gives 0x000000FE. Its unsigned value is 254, and since its top bit is now 0, its signed value is also 254: the unsigned reading survived and the signed reading changed.

Sign extension copies bit 7, which is 1, into bits 8 to 31, giving 0xFFFFFFFE. Read as unsigned, that is 232−2=4,294,967,2942^{32} - 2 = 4{,}294{,}967{,}294. Read as two’s complement, it is 4,294,967,294−232=−24{,}294{,}967{,}294 - 2^{32} = -2: the signed reading survived. For 0x7E, whose bit 7 is 0, both extensions give 0x0000007E, the value 126.

Truncation: the 32-bit value 70,000 is 0x00011170, because 70,000=1×65,536+4,46470{,}000 = 1 \times 65{,}536 + 4{,}464 and 4,464 is 0x1170. Keeping the low 16 bits gives 0x1170, the value 70,000mod65,536=4,46470{,}000 \bmod 65{,}536 = 4{,}464. A protocol that limits the field to 8,192 would accept 4,464; the limit check had to run on 70,000, before the truncation.

A C bug that combines the two: on x86, where plain char is signed, a char c holding the byte 0xFE has the value −2-2. The expression table[c] promotes c to int by sign extension and reads table[-2], two elements before the start of the array §14.5. Writing table[(unsigned char)c] zero-extends instead and reads element 254.

Stated precisely

Let xx be a ww-bit pattern with bits b0,…,bw−1b_0, \dots, b_{w-1}. Write Uw(x)=∑i=0w−1bi2iU_w(x) = \sum_{i=0}^{w-1} b_i 2^i for its unsigned value and Sw(x)=Uw(x)−bw−12wS_w(x) = U_w(x) - b_{w-1} 2^w for its two’s-complement value; the second formula is the first with the top bit’s weight changed from +2w−1+2^{w-1} to −2w−1-2^{w-1}. For a wider width v>wv > w, the zero extension zz of xx satisfies Uv(z)=Uw(x)U_v(z) = U_w(x), and the sign extension ss of xx satisfies Sv(s)=Sw(x)S_v(s) = S_w(x). For a narrower width v<wv < w, the truncation tt of xx satisfies Uv(t)=Uw(x)mod2vU_v(t) = U_w(x) \bmod 2^v, and Sv(t)=Sw(x)S_v(t) = S_w(x) exactly when −2v−1≤Sw(x)≤2v−1−1-2^{v-1} \le S_w(x) \le 2^{v-1} - 1.

Proof for sign extension. Write b=bw−1b = b_{w-1}. The new bits ww to v−1v - 1 all equal bb, so Uv(s)=Uw(x)+b(2w+2w+1+…+2v−1)=Uw(x)+b(2v−2w)U_v(s) = U_w(x) + b\,(2^w + 2^{w+1} + \dots + 2^{v-1}) = U_w(x) + b\,(2^v - 2^w). The new top bit is also bb, so Sv(s)=Uv(s)−b2v=Uw(x)−b2w=Sw(x)S_v(s) = U_v(s) - b\,2^v = U_w(x) - b\,2^w = S_w(x). With xx the byte 0xFE, w=8w = 8, v=32v = 32 and b=1b = 1: U32(s)=254+232−28=4,294,967,294U_{32}(s) = 254 + 2^{32} - 2^8 = 4{,}294{,}967{,}294, and S32(s)=4,294,967,294−232=−2=S8(x)S_{32}(s) = 4{,}294{,}967{,}294 - 2^{32} = -2 = S_8(x).

Limits and common mistakes

Choosing the wrong extension is a common bug. The Common Weakness Enumeration (CWE), a public catalog of software weaknesses, lists it as CWE-194, unexpected sign extension, and lists lost high-order bits as CWE-197, numeric truncation error.

Converting a negative signed value to a wider unsigned type gives the sign-extended pattern: (uint32_t)(int8_t)-2 is 0xFFFFFFFE. To get 0x000000FE from an int8_t value x, convert to uint8_t first: (uint32_t)(uint8_t)x.

Check before narrowing. After truncation the discarded bits are gone, and no test on the narrow value can recover them.

Truncating and then sign-extending returns the original value only if it fitted. GCC stores 200 in an int8_t as −56-56, and widening −56-56 back to int gives −56-56, not 200.

The word truncation has other meanings. Converting a floating-point value to an integer in C truncates the fraction, which rounds toward zero, so (int)-2.7 is −2-2. Tag truncation §5.12 in cryptography shortens an authentication §1.6 tag. Neither is the bit-level operation described here.

A C conversion describes a value, not an instruction: the compiler may implement it with a sign-extending load, a zero-extending load or no instruction at all.

Questions answered

How does sign-extending an 8-bit value differ from zero-extending it?

Sign extension and zero extension differ in what they put into the new high-order bits, and therefore in which reading of the 8 bits they preserve. Zero extension fills every new bit with 0, which keeps the value of the byte read as unsigned (0 to 255). Sign extension fills every new bit with a copy of bit 7, the sign bit, which keeps the value of the byte read as a signed two’s-complement number (−128-128 to 127), the encoding in which bit 7 counts −128-128. For the byte 0xFE, zero extension to 32 bits gives 0x000000FE, which is 254, and sign extension gives 0xFFFFFFFE, which is −2-2 as a signed 32-bit number. For bytes whose bit 7 is 0, the values 0 to 127, the two give the same result.

Use zero extension for quantities that cannot be negative, such as lengths and raw byte values, and sign extension for signed quantities, such as offsets or temperatures. Instruction sets provide both, for example LDRB and LDRSB on Arm. In C the compiler chooses from the source type: uint8_t and unsigned char are zero-extended, int8_t and signed char are sign-extended, and plain char depends on the platform.

Related entries: Signed versus unsigned comparison (§2.12), Integer promotion and conversion (§4.18), ALU32 versus ALU64 (§2.11), Unsigned modular arithmetic (§4.16). Further reading: [78, 160].