3

I want to perform addition modulo 2 to the power 64 between p1 and p2 using MATLAB. Both p1 and p2 are of type uint64. Is the following code correct?

c1 = p1 + p2;
if (c1> 2^64)
    c1 = c1 - 2^64;
end
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Naseem
  • 39
  • 6

1 Answers1

4

The maximum value of variables of uint64 type is 2^64-1 (in Matlab, intmax('uint64')) and when you do an addition operation that exceeds this value (overflow) then the result is 2^64-1, so your code will not work.

For example:

p1 = uint64(2^64-1) - 5;
p2 = uint64(10);
c1 = p1 + p2;

The result of c1 is:

>> c1 =

  uint64

   18446744073709551615

which is 2^64-1 (and not 2^64-1 + 5)

And The result of c1-p1 is:

>> c1-p1

ans =

  uint64

   5

But it should have been 10

Workaround:

You can check before the addition if there will be an overflow and if so, calculate the remainder:

intmaxDif = intmax('uint64') - p1;
if(p2  > intmaxDif)
    c1 = p2 - intmaxDif - 1;
else
    c1  = p1 + p2;
end

This code will perform addition modulo 2 to the power 64 between p1 and p2

Thanks to Cris Luengo on the correction.

Community
  • 1
  • 1
Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37