BigInt to hex and back to Bigint


Trying to convert hexadecimal strings of VERY big positive numbers back to integers but so far no good.

Tried with hex2num but i get an overflow as number is too big.


julia.exe --check-bounds=yes --depwarn=yes --math-mode=ieee --optimize test.jl
ERROR: LoadError: OverflowError()
in tryparse_internal(::Type{UInt64}, ::String, ::Int64, ::Int64, ::Int64, ::Bool) at .\parse.jl:114

in parse(::Type{UInt64}, ::String, ::Int64) at .\parse.jl:150
in hex2num(::String) at .\floatfuncs.jl:40
in include_from_node1(::String) at .\loading.jl:488
in process_options(::Base.JLOptions) at .\client.jl:265
in _start() at .\client.jl:321

In python I can convert this hex into integer with “int(hexnum, 16)”.
Any suggestion on how to parse this kind of big integers from and to hex?


This seems to do the trick (with str your long hex string):

parse(BigInt, str, 16)


Perhaps the Base implementation should be more robust to the possible integer overflow?


Started playing with julia last week and haven’t thought of using parse.Thank you!

In case someone is interested, this is what I have working now.

function hex2int(hexstring)
  if isodd(length(hexstring))
    throw("hex string must be even")
  local number = BigInt(1)
    number = parse(BigInt, hexstring, 16)
    throw("ValueError: hex string cannot be converted to integer.")
  return BigInt(number)

function int2hex(integer)
  local hexstring = string(hex(integer))
  if isodd(length(hexstring))
    throw("AssertionError: integer conversion produced invalid hex string.")
  return hexstring

Should do the trick but let me know if you think otherwise.


Your int2hex will fail for numbers with an odd number of hex digits (eg 1). I am not sure this is intended (it is still a valid representation even with an odd number of digits). If you want to pad with 0s to an even number of digits, try using the second argument of hex.

As for hex2int, generally it is OK to just let errors propagate up the stack instead of catching and throwing something else.