x86 versus ARM gotcha

Discussions related to mathematics, numerical methods, graph plotting etc.
Hated Moron

x86 versus ARM gotcha

Post by Hated Moron »

I may have mentioned this before, but as I'd forgotten (and got caught out by it) so might you!

Modern BBC BASICs (both mine and Michael McConnell's Matrix Brandy) support signed 64-bit integer variables, represented by a double % suffix, e.g. a%%. Such variables can hold any whole number from -2^63 (-9223372036854775808) to 2^63-1 (9223372036854775807) inclusive.

So you might think that this code would be entirely valid, but it isn't:

Code: Select all

a%% = 2^63 - 1
The reason it isn't valid is that although 2^63 -1 can be stored in a 64-bit integer, 2^63 can't. So when the expression evaluator performs the calculation it first evaluates 2^63 (which since it cannot fit in an integer gets represented as a float) and then it subtracts one, but by then it's too late, it's already a float!

To solve this problem you could, for example, perform the assignment as follows:

Code: Select all

a%% = 2^62 - 1 + 2^62
Now none of the individual terms of the expression are too big to fit in an integer, the calculation remains integer throughout, and the assignment succeeds.

The 'gotcha' comes from the fact that the first example above does actually work when performed on an x86 CPU, but it fails when performed on an ARM CPU. The reason is that the x86 has 80-bit floats and the ARM has only 64-bit floats. So you could include it in a program which you test, say, in Windows only to find it fails when run on a Raspberry Pi.

Just something to be aware of (although I'm almost certain to forget again).