top | item 43663032

(no title)

FractalFir | 10 months ago

Correct me if I am wrong C, unsigned overflow is well-defined - at least the GCC manual says so, but I'll have to check the standard.

https://www.gnu.org/software/c-intro-and-ref/manual/html_nod...

Since signed multiplication is bitwise-equivalent to unsigned multiplication, I use unsigned multiplication to emulate UB-free signed multiplication. The signed variant of this overflow check is a bit harder to read because of that, but it still works just fine.

bool i128_mul_ovf_check(__int128 A0 ,__int128 A1 ){

bb0:

if((A1) != (0)) goto bb1;

return false;

bb1:

return (((__int128)((__uint128_t)(A0) * (__uint128_t)(A1))) / (A1)) == (A1);

}

As for using `__builtin_popcountll` instead - you are right, my mistake. Thanks for pointing that out :).

I did not use the word "unsigned" before long long for the sake of readability - I know that repeating a word so many times can make it harder to parse for some folk. The project itself uses the correct types in the code, I was just kind of loose with the language in the article itself. My bad, I'll fix that and be a bit more accurate.

Once again, thanks for the feedback!

discuss

order

tialaramex|10 months ago

Yes, the C and C++ unsigned types are analogous to Rust's Wrapping<u8> Wrapping<u16> Wrapping<u32> and so on, except that their size isn't nailed down by the ISO document.