Failed to convert hex string to UInt256

I wrote this function convert hex strings to UInt256 and got an error. Can anyone help me fix it?

fn to_UInt256(hex_string: String) raises -> UInt256:
    builtins = Python.import_module("builtins")
    return UInt256(builtins.int(hex_string, 16))
error: cannot implicitly convert 'SIMD[float64, 1]' value to 'SIMD[ui256, 1]'
    return UInt256(builtins.int(hex_string, 16))
           ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A UInt256 is an alias to SIMD[DType.uint256, 1]. And SIMD only has one constructor from a PythonObject, which returns a Float64.

So the PythonObject is implicitly converted to a Float64, but you can’t implicitly convert a Float64 to a UInt256, you’d have to cast it. Also it’s not wide enough if you really need a 256. I don’t think there’s currently a way to go from PythonObject to a UInt256 that isn’t lossy at the moment.

2 Likes

This is related to what Sora described in your other post: Failed to use Python hex() function in Mojo - #2 by sora

1 Like