expression

Protocol Buffers: ZigZag for sint32

ZigZag maps signed integers to unsigned values so small magnitudes on either side of zero stay small. sint32 uses this transformation before varint encoding; int32 does not. This example computes the mapping only. Expected stdout (not executed): 0: 0 -1: 1 1: 2 -2: 3 2: 4 -2147483648: 4294967295 Common mistake: Changing an existing int32 field to sint32 and expecting old encoded values to keep their meaning.

Formal Syntax & Structure

rust syntaxrust
((value as u32) << 1) ^ ((value >> 31) as u32)

Working Example

Example Snippetrust
fn main() {    fn zigzag(value: i32) -> u32 {        ((value as u32) << 1) ^ ((value >> 31) as u32)    }    for value in [0, -1, 1, -2, 2, i32::MIN] {        println!("{value}: {}", zigzag(value));    }}
Rust Reference