by pixelfarmer · 1y ago · 0 comments
Also, if a * b overflows within the result type, it is an undefined behavior according to the C standard, so this overflow check is at least not properly portable, either, and the shown code for that is actually buggy because the last A1 has to be A0.
No idea why all that gets me so grumpy today ...
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!