Date: Thu, 12 Jun 2025 15:08:59 +0200
OK. If it overflows, one can set the quotient to 𝛽 - 1, where 𝛽 is the base, or -1 in an unsigned type, and the remainder, if needed, can be computed from that. Currently, I do not use the remainder, but just check if the product overflows, and if it does, reduce the quotient with 1, repeating at most once. In a suggested algorithm, the quotient approximation can be sharpened to overflow with at most 1 by looking at the words next below in the divisor and dividend.
> On 12 Jun 2025, at 14:50, Tiago Freire <tmiguelf_at_[hidden]> wrote:
>
> Ok,
> x86 doesn't have an overflow flag for this operation, it just traps and you doesn't even get a result. Other CPUs just don't have the instruction.
> In any case the solution is very simple.
> Of unsigned integers, In order to detect the overflow all you have to do in your example:
>
> a1 >= b
>
> that's it
> For unsigned integers it doesn't really matter at all what bits are set in your low dividend.
> Mathematically if a1 >= b it is guaranteed to overflow, and a1 < b it is guaranteed to not overflow.
> If you also can guarantee that the most significant bit of 'b' is set (and this condition is extremely important otherwise the following won't work), then you can just do this:
>
> if(a1 < b)
> { //no overflow
> auto result = div_wide(a1, a0, b);
> }
> else //overflow
> {
> auto result = div_wide(a1 - b , a0, b);
> //extra bit handling goes here
> }
>
> Otherwise you would have to break down into 2 divisions as mentioned before.
> On 12 Jun 2025, at 14:50, Tiago Freire <tmiguelf_at_[hidden]> wrote:
>
> Ok,
> x86 doesn't have an overflow flag for this operation, it just traps and you doesn't even get a result. Other CPUs just don't have the instruction.
> In any case the solution is very simple.
> Of unsigned integers, In order to detect the overflow all you have to do in your example:
>
> a1 >= b
>
> that's it
> For unsigned integers it doesn't really matter at all what bits are set in your low dividend.
> Mathematically if a1 >= b it is guaranteed to overflow, and a1 < b it is guaranteed to not overflow.
> If you also can guarantee that the most significant bit of 'b' is set (and this condition is extremely important otherwise the following won't work), then you can just do this:
>
> if(a1 < b)
> { //no overflow
> auto result = div_wide(a1, a0, b);
> }
> else //overflow
> {
> auto result = div_wide(a1 - b , a0, b);
> //extra bit handling goes here
> }
>
> Otherwise you would have to break down into 2 divisions as mentioned before.
Received on 2025-06-12 13:12:19