0

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?

6
  • Just asking: You are aware of the implications, right? Bigint Range is way larger than e.g. int range. Commented Feb 11, 2024 at 20:00
  • 4
    int32(bigVal.Int64())? pretty trivial imho. Commented Feb 11, 2024 at 20:02
  • @ErhardDinhobl yes I am aware of the implications, but there is no risk of overflow because I am using Mod on the number before I try to convert it. Commented Feb 11, 2024 at 20:02
  • 1
    Have you tried theBigInt.Int()? I remember slt. I am not that familiar with Go but i once read the docs. Commented Feb 11, 2024 at 20:04
  • 6
    Would consulting the documentation of math/big.Int be an option? Commented Feb 11, 2024 at 20:11

1 Answer 1

0

@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())

Sign up to request clarification or add additional context in comments.

1 Comment

Int64() doesn't "return undefined" in the sense of returning a value that identifies that the value is undefined. "undefined" in this context is not the same as, say, "NaN", in the context of a float, for example. Rather, the return value being "undefined" is a warning that there is no contract or specification for what is returned in that case; your code should not rely on that the current implementation happens to return in such cases (i.e. always the lowest 64 bits of the value). It could change in the future, e.g. to return 0 or -1 etc for some reason (e.g. efficiency).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.