I want to do an unchecked multiply, so that it does not return an error when multiplying and instead just discard the bits.
code:
102 let count: u64 = (((b + (b >> 4)) & 0xF0F0F0F0F0F0F0Fu64) * 0x101010101010101u64) >> 56;
Error:
thread 'main' panicked at 'attempt to multiply with overflow', src/main.rs:102:22
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
What is the simplest way to do this?
BTW: the algorithm that I am trying to implement is this one: https://stackoverflow.com/a/2709523/20532471
You do not want unchecked_mul()
, you really do not. It causes UB on overflow, while you just want to discard the overflowing bits.
What you need is wrapping_mul()
:
let count: u64 = (((b + (b >> 4)) & 0xF0F0F0F0F0F0F0Fu64).wrapping_mul(0x101010101010101u64)) >> 56;