【Move语法问题】如何将一个u64整型转为字符串? #234
Answered
by
qiwihui
xiegudong45
asked this question in
Q&A
-
如题,想将一个u64整型转为字符串,比如,输入1, 返回"1";输入12,返回"12",应该如何转换? |
Beta Was this translation helpful? Give feedback.
Answered by
qiwihui
Jan 12, 2023
Replies: 3 comments 1 reply
-
补充: u64 版本 use std::string::{Self, String};
use std::vector;
/// @dev Converts a `u64` to its `ascii::String` decimal representation.
public fun to_string(value: u64): String {
if (value == 0) {
return string::utf8(b"0")
};
let buffer = vector::empty<u8>();
while (value != 0) {
vector::push_back(&mut buffer, ((48 + value % 10) as u8));
value = value / 10;
};
vector::reverse(&mut buffer);
string::utf8(buffer)
}
/// @dev Converts a `ascii::String` to its `u64` decimal representation.
public fun to_integer(s: String): u64 {
let res = 0;
let s_bytes = *string::bytes(&s);
let i = 0;
let k: u64 = 1;
while (i < vector::length(&s_bytes)) {
let n = vector::pop_back(&mut s_bytes);
res = res + ((n as u64) - 48) * k;
k = k * 10;
i = i + 1;
};
res
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
xiegudong45
-
补充一下,我的代码问题有2个
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
补充: u64 版本