How to do unchecked multiply in rust?

424 Views Asked by At

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

2

There are 2 best solutions below

0
Chayim Friedman On BEST ANSWER

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;
0
hobrin On

I found a quick and dirty workaround. Basically just use a u128 which just about fits all my data that theoretically can be the product, and then convert that back to a u64.

Here is the updated line:

    let count: u64 = ((((b + (b >> 4)) as u128 & 0xF0F0F0F0F0F0F0Fu128) * 0x101010101010101u128) & ((1<<64)-1)) as u64 >> 56;