Converting u64 to u256 and vice versa

I’m looking to convert u64 to u256 and vice versa for the Fraction library. I’m unable to find the documentation and reverse engineering the core libs isn’t working out. I was wondering if someone could share the steps needed for this conversion. Thanks

If 10 is your number for example

10_u64.as_u256()

This pattern should work for all unsigned integers for converting between the current size and a bigger size. Aka u8 → u16 would be

10_u8.as_u16()

You can see the underlying code here

2 Likes

Thanks. Now I can convert u64 to u256. But I also need the reverse conversion. I’ve tried

  1. x.try_into().unwrap()
  2. x.as_u64()
  3. x.to_u64()
  4. x.d
  5. let (a, b, c, d) = x

Where x is of the type u256 but nothing worked.

As the reverse conversions are lossy, the standard library offers methods that return an option.

u64::try_from(x)

This will return an option, you can match on it or unwrap it.

Doesn’t work for me. Maybe I did something wrong. I’m trying:

let np = u64::try_from((an*bn*factor.as_u256())/(ad*bd)).unwrap();

where all the variables used in the middle are of the nature u256. The error message is:
^^^^^^^^ No method named “try_from” found for type “u64”

I haven’t imported u64 at the top of the file after library; because I don’t believe we have to import primitive types. Am I doing something wrong?

Here is the concerned erroring line (ignore the other errors, they only appear when this function isn’t commented out).

You dont have to import the type but you do have to import the methods, as they are not imported by default.

use std::primitive_conversions::u64::*;

Should work

1 Like

After some changes in addition to that, this error went away. Maybe we could somehow add this to the official documentation?

Hi there :palm_tree:
I’m adding this documentation request to the backlog
thanks for your report.