Reputation: 12500
I'm trying to perform some 64 bit
additions, ie:
a = 0x15151515
b = 0xFFFFFFFF
c = a + b
print hex(c)
My problem is that the above outputs:
0x115151514
I would like the addition to be 64 bit
and disregard the overflow, ie expected output would be:
0x15151514
NB: I'm not looking to truncate the string output, I would like c = 0x15151514
. I'm trying to simulator some 64 bit register operations.
Upvotes: 2
Views: 2298
Reputation: 4002
Another solution using numpy:
import numpy as np
a = np.array([0x15151515], dtype=np.uint32) # use np.uint64 for 64 bits operations
b = np.array([0xFFFFFFFF], dtype=np.uint32)
c = a + b
print(c, c.dtype)
[353703188] uint32
pros: more readable than binary mask if many operations, especially if other operations such as division are used in which case you cannot just apply the mask at the final result but also need to apply it at intermediary operations ex: (0xFFFFFFFF + 1) // 2)
cons: adds a dependency, requires to be careful with literals:
c = a + 2**32 # 2**32 does not fit in np.uint32 so numpy changes the type of c
print(c, c.dtype)
[4648670485] uint64
Upvotes: 0
Reputation: 36337
Then just use the logical and operator &
c = 0xFFFFFFFF & (a+b)
By the way, these are 32 bit values, not 64 bit values (count the F
; every two F
is one byte == 8 bit; it's eight F
, so four byte, so 32 bit).
Upvotes: 6