Demoting BigInt to Int64

I need to read some numbers from a file and then do things with them. In theory I may get numbers that are bigger than 2^{128} so I parse them as BigInt. However, usually they are smaller than 2^{63} so Int64 is enough.

My “solution” was to parse them as BigInt and then demote them to Int64 if they are not too big. Then I can create my structure and go do my thing. The problem with this is that parse does not want to change BigInt to Int64. This is reasonable since it will usually fail, but in this case it won’t. Is there any way to do that or I have to parse them as Int64 and start catching errors?

Instead of catching errors, I would suggest using tryparse.

1 Like

I just realised that the easiest fix is to parse them twice. I can parse them once as BigInt, check how big they are and parse them again with the correct type. :slight_smile:

can’t you do something like:

# a is BigInt

a = a<=typemax(Int64) ? Int64(a) : a
1 Like

Doesn’t this call parse?

EDIT: It seems it doesn’t. I just tried it. I thought that all type conversions were done through parse.

no, parse is used to ‘parse’ literal “text” into numerical bits. Once you have the number, you can do computer-stuff


It’s really better to use tryparse(Int, a), and parse to BigInt only if that returns nothing. Parsing to BigInt is much slower, so go for tryparse.

Should also compare to typemin(Int), but no need for this anyway, if using tryparse(Int, ...)