Skip to content

Instantly share code, notes, and snippets.

@eNipu
Created February 4, 2022 11:20
Show Gist options
  • Select an option

  • Save eNipu/6e8c3917865a4eb1e8cb34184d954d28 to your computer and use it in GitHub Desktop.

Select an option

Save eNipu/6e8c3917865a4eb1e8cb34184d954d28 to your computer and use it in GitHub Desktop.
overage without overflow
fn average_without_overflow(a: i32, b: i32) -> i32 {
return (a & b) + ((a ^ b) >> 1);
}
fn average_with_overflow(a: i32, b: i32) -> i32 {
let avg = (a+b)/2;
return avg;
}
fn main() {
let a = std::i32::MAX;
let b = 1i32;
println!("a={}, b={}", a, b);
let c = average_without_overflow(a, b);
println!("Average without overflow: {}", c);
/* Output
a=2147483647, b=1
Average without overflow: 1073741824
*/
let c = average_with_overflow(a, b);
println!("Average with overflow: {}", c);
/*
thread 'main' panicked at 'attempt to add with overflow', src/main.rs
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment