Manipulate 64-bit value with 32-bit registers

Last updated on April 15, 2023 am

Manipulate 64-bit value with 32-bit registers

Say, a 64-bit unsigned integer is stored at two 32-bit registers, s0 (lower bits) and s1 (higher bits) respectively.

Addition

And now, we need to add a 32-bit unsigned integer stored at register t0 to it, how could we do.

Recall the feature of two’s complement in binary, integer overflow is same as left a carry forgotten.

1
2
3
4
mv          t1, s0      # save a copy of lower bits
add s0, s0, t0 # add to lower bits
sltu t2, s0, t1 # check for carry
addi s1, s1, t2 # add carry

Here sltu stands for set less than unsigned, meaning that if s0 is less than t1, t2 will be set to 1, otherwise, t2 will be 0. This is just what we need.

If the new lower 32 bits is smaller than the original one (at t1), meaning there is an overflow, so we should increase the higher 32 bits s1 by 1.

Subtraction

This can also apply to subtraction.

1
2
3
4
5
mv          t1, s0
sub s0, s0, t1
sltu t2, s0, t1
addi t2, t2, 1
add s1, s1, t2

More Details

Take 4 bits and 8 bits as an example.

Meaning binary decimal
1. 8 bits unsigned integer 0x0001_0101 21
2. 4 bits unsigned integer t0 0x0111 7
3. difference in 8 bits 0x0000_1110 14
4. opposite number of t0 0x1001 -
5. add 4 to lower bits 0x1110 -

If borrow occurred, value in 5 will greater than the lower bits of the original number.

In other words, if new lower bits is less than the original one, t2 will be set to 1 and then 0, there is no borrow. Otherwise, t2 will be set to 0 and then -1, take away one from higher bits.


Manipulate 64-bit value with 32-bit registers
https://lingkang.dev/2023/04/15/64bit-val-in-32/
Author
Lingkang
Posted on
April 15, 2023
Licensed under