Walrfi
Walrfi

Reputation: 121

Store temporary 64 bit variable in a 32 bit machine

I'm doing some programming on a 32bit machine. As part of an algorithm to calculate collisions between objects in 3d I have to get the results of a dot product:

    //Vector3 components are signed int
    signed long GaMhVecDotL(const Vector3 *p_a, const Vector3 *p_b)
    {
        return ((p_a->vx * p_b->vx + p_a->vy * p_b->vy + p_a->vz * p_b->vz));
    }

In some cases this result overflows the 32 bit returning value (signed long). I have tried a couple of things:

  1. Bitshift the Vector3 components before sending them to this function to reduce the size. This works in most cases but I lose precision and that makes the algorithm fail in some edge cases.
  2. Storing the result of the operation in a long long variable, and although it compiles it doesn't seem to store the variables correctly (this is for some PSX homebrew, compiler and tools haven't been updated since the late 90s).

I actually don't need to know the full result of the Dot Product, I would just need to know if the result is positive, negative or 0 and at the same time trying to preserve as much precision as possible.

Is there any way I can store the result of that operation (p_a->vx * p_b->vx + p_a->vy * p_b->vy + p_a->vz * p_b->vz) in a temp 64 bit var (or 2x32 bit) that would allow me later to check if this var is positive, negative or 0?

Upvotes: 0

Views: 713

Answers (1)

chux
chux

Reputation: 153303

Is there any way I can store the result of that operation (p_a->vx * p_b->vx + p_a->vy * p_b->vy + p_a->vz * p_b->vz) in a temp 64 bit var (or 2x32 bit) that would allow me later to check if this var is positive, negative or 0?

This uses 32-bit math, (given int is 32-bit). Storing the return in a 64-bit result does not make the equation 64-bit.

// 32-bit math
p_a->vx * p_b->vx + p_a->vy * p_b->vy + p_a->vz * p_b->vz

Instead, use 64 bit math in the equation.

//               v-----------------v multiplication now done as 64-bit
long long dot = (1LL*p_a->vx*p_b->vx) + (1LL*p_a->vy*p_b->vy) + (1LL*p_a->vz*p_b->vz);

Then check sign-ness

if (dot < 0) return -1;
return dot > 0;

Upvotes: 3

Related Questions