0

How do I convert U256 to different types using alloy primitives?

For example

let num = U256::from(42_u8);

In ethers it's simple, num.to_u128() but how to do it in alloy?

New contributor
Bharath is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

1 Answer 1

0

In alloy you use .to::< > turbofish to convert between types

    let num = U256::from(42_u8);

    let a: u128 = num.to::<u128>();
    assert_eq!(a, 42);

    let b: u64 = num.to::<u64>();
    assert_eq!(b, 42);

    let c: u32 = num.to::<u32>();
    assert_eq!(c, 42);

    let d: usize = num.to::<usize>();
    assert_eq!(d, 42);

    let e: String = num.to_string();
    assert_eq!(e, "42");

    let f: String = format_units(num, 4)?;
    assert_eq!(f, "0.0042");

This is not pretty straight forward from google search, keeping it here for future references.

Source : Github

New contributor
Bharath is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.