Go: convert big.Int to regular integer (int, int32, int64)

82 Views Asked by At

I assumed this would be a simple issue with abundant answers on the Internet. But that does not appear to be the case.

I need to convert a Go big.Int into a regular integer (e.g., int, int32, or int64). But there appears to be no straightforward way to do this.

I've tried int(bigVal), int32(bigVal), and int64(bigVal), but they give the error cannot convert bigVal(variable of type big.Int) to type x (where x is either int, int32 or int64).

I'm finding myself frustrated over how Go makes handling big numbers so complicated (in contrast to the relative ease of, say, C#/.NET's System.Numerics.BigInteger). How do I accomplish this, something that should a trivially easy task?

1

There are 1 best solutions below

1
Cade Bryant On

@Eldar was correct. Thank you! big.Int has an instance-level method called Int64() that returns the 64-bit integer representation of the value (or undefined if it cannot be represented as such).

I merely needed to wrap it wothint32() to get the desired result:

int32(bigVal.Int64())