Convert u256 to string

hey @nick I am trying to concat a string and s u256. I was trying to do this: Convert u64 to String for concatenation - #2 by Serafim

This is the relevent code that I wrote:

pub fn concat_str_with_num(s: String, num: u256) -> String {
    let mut result = Bytes::new();
    push_bytes(result, s.as_bytes());
    push_bytes(result, String::from_ascii_str("/").as_bytes()); // an arbitrary delimeter
    push_bytes(result, convert_num_to_ascii_bytes(num));
    String::from_ascii(result)
}

fn convert_num_to_ascii_bytes(num: u256) -> Bytes {
    let mut bytes = Bytes::new();
    let mut n = num;
    if n == 0 {
        bytes.push(48);
        return bytes;
    }
    while n != 0 {
        // 48 - is an ASCII offset for digits
        bytes.push(((n % 10) + 48).try_as_u8().unwrap());
        n /= 10;
    }
    let mut reversed_bytes = Bytes::with_capacity(bytes.len());
    while !bytes.is_empty() {
        reversed_bytes.push(bytes.pop().unwrap());
    }
    return reversed_bytes;
}

fn push_bytes(ref mut a: Bytes, b: Bytes) {
    let mut i = 0;
    while i < b.len() {
        a.push(b.get(i).unwrap());
        i = i + 1;
    }
}

I am getting this error:

    |
188 |
189 |         // 48 - is an ASCII offset for digits
190 |         bytes.push(((n % 10) + 48).try_as_u8().unwrap());
    |                                    ^^^^^^^^^ No method named "try_as_u8" found for type "u256".
191 |         n /= 10;
192 |     }
    |
____


Is there some import that I am missing?

Here are my imports:

use std::primitive_conversions::u256::*;
use sway_libs::{
       ownership::{
        _owner,
        initialize_ownership,
        only_owner,
    },
    asset::metadata::*,
    reentrancy::*
};

use standards::{
    src5::{SRC5, State, AccessError},
    src20::SRC20,
    src7::{SRC7, Metadata}
};

use std::{
    asset::{
        burn,
        mint_to,
        transfer,
    },
    call_frames::{
        msg_asset_id,
    },
    constants::DEFAULT_SUB_ID,
    context::msg_amount,
    string::String,
    hash::Hash,
    storage::storage_map::StorageMap,
    storage::storage_string::StorageString,
    bytes::*
};

1 Like