Sign extension for converting smaller signed integers to 256-bit signed representation
This page is a placeholder. All examples on this page are currently AI-generated and are not correct. This documentation will be completed in the future with accurate, tested examples.
Overview
Opcode:0x0bIntroduced: Frontier (EVM genesis)SIGNEXTEND extends the sign bit of a value stored in fewer than 32 bytes to fill the full 256-bit word. This operation converts smaller signed integers (int8, int16, etc.) to the full int256 representation required for signed arithmetic operations in the EVM.The operation is critical for handling signed integer types smaller than 256 bits, particularly when interfacing with external systems or optimizing storage.
Specification
Stack Input:
byte_index (top)value
Stack Output:
sign_extended_value
Gas Cost: 5 (GasFastStep)Operation:
if byte_index >= 31: result = value // No extension neededelse: sign_bit_position = byte_index * 8 + 7 if bit at sign_bit_position is 1: // Sign extend with 1s result = value | ~((1 << (sign_bit_position + 1)) - 1) else: // Zero extend (clear upper bits) result = value & ((1 << (sign_bit_position + 1)) - 1)
Behavior
SIGNEXTEND pops two values from the stack:
byte_index - Which byte contains the sign bit (0 = rightmost byte)
value - The value to sign-extend
The sign bit is at position byte_index * 8 + 7 (the MSB of that byte):
If sign bit = 1: Fill upper bits with 1s (negative number)
If sign bit = 0: Clear upper bits to 0 (positive number)
If byte_index >= 31: Return value unchanged (already 256-bit)
int8 value = -1 = 0xFFint256 extended = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
Both represent -1 in their respective sizes.
ABI Compatibility
Essential for correctly decoding signed integer types from ABI-encoded calldata:
// Correct handling of int8 from calldatafunction handleInt8(int8 x) external { assembly { let val := calldataload(4) // Load after selector val := signextend(0, val) // Extend sign // Now val is correct int256 representation }}
Storage Optimization Safety
When packing signed values, SIGNEXTEND ensures correct unpacking:
// CORRECT: Sign extensionfunction unpack(bytes32 slot) pure returns (int8) { assembly { let val := and(slot, 0xFF) val := signextend(0, val) // Must sign extend mstore(0x00, val) return(0x00, 0x20) }}// WRONG: No sign extensionfunction unpackWrong(bytes32 slot) pure returns (int8) { assembly { let val := and(slot, 0xFF) // Missing signextend - negative values become positive! mstore(0x00, val) return(0x00, 0x20) }}
Type Safety
SIGNEXTEND is critical for maintaining type safety across different integer sizes:
Prevents incorrect interpretation of negative values
Ensures arithmetic operations produce correct results