Asked by Ansam Osamah
on 18 Sep 2019

I encrypt uint64 numbers. Number x which encrypted as, for example, 9824265115183455531 decrypted as 9824265115183455488. This difference affects the final decrypted text. Is Matlab not gives accurate results when operates on uint64? how I overcome this problem?

Answer by Steven Lord
on 18 Sep 2019

Accepted Answer

It really depends on how you performed your computations. Let's take a somewhat large number, 3^40.

xDouble = 3^40;

xUint64 = uint64(3)^40;

areTheseTheSame = [uint64(xDouble); xUint64]

The answer to the implied question is no. The reason the two elements of areTheseTheSame are not the same is that 3^40 is greater than flintmax.

isGreaterThanFlintmax = xDouble > flintmax % true

The key statement in the flintmax documentation is "Above this value, double-precision format does not have integer precision, and not all integers can be represented exactly." The next largest representable number above flintmax is not flintmax+1 but flintmax+2.

>> F1 = flintmax;

>> F2 = flintmax + 1;

>> F1 == F2

ans =

logical

1

>> eps(flintmax)

ans =

2

>> F3 = flintmax + 2;

>> F1 == F3

ans =

logical

0

However, 3^40 is less than the maximum value that you can store in a uint64 so it can be exactly represented in uint64.

isLessThanMaximumUint64 = xUint64 < intmax('uint64') % true

If your computations are likely to result in large (greater than flintmax) integer values, you should probably operate on values stored in an integer data type as much as you can, like I did when I computed xUint64 by computing mpower (the ^ operator) on a uint64 value.

Ansam Osamah
on 20 Sep 2019

Thank you very much

But, what about dec2bin for uint64

K>> dec2bin(uint64(8417341953491579463),64)

ans =

0111010011010000011001111110100011100010110110111011010000000000

but it is actually

0111010011010000011001111110100011100010110110111011001001000111

Walter Roberson
on 20 Sep 2019

dec2bin() converts its input to double before working out the binary.

u64 = uint64(8417341953491579463);

reshape(dec2bin(typecast(swapbytes(u64),'uint8'),8).',1,[])

Ansam Osamah
on 20 Sep 2019

Thank you very much to all, your advice helped me too much

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 4 Comments

## James Tursa (view profile)

## Direct link to this comment

https://de.mathworks.com/matlabcentral/answers/480862-accuracy-problems-in-uint64-numbers#comment_747086

## Walter Roberson (view profile)

## Direct link to this comment

https://de.mathworks.com/matlabcentral/answers/480862-accuracy-problems-in-uint64-numbers#comment_747089

## Ansam Osamah (view profile)

## Direct link to this comment

https://de.mathworks.com/matlabcentral/answers/480862-accuracy-problems-in-uint64-numbers#comment_747127

## Walter Roberson (view profile)

## Direct link to this comment

https://de.mathworks.com/matlabcentral/answers/480862-accuracy-problems-in-uint64-numbers#comment_747132

Sign in to comment.