MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / base_converter

Function base_converter

code/chapter03/base_converter.rs:31–52  ·  view source on GitHub ↗
(mut dec_num: u32, base: u32)

Source from the content-addressed store, hash-verified

29}
30
31fn base_converter(mut dec_num: u32, base: u32) -> String {
32 // digits 对应各种余数的字符形式,尤其是 10 - 15
33 let digits = ['0', '1', '2', '3', '4', '5', '6', '7',
34 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
35
36 // 余数入栈
37 let mut rem_stack = Stack::new();
38 while dec_num > 0 {
39 let rem = dec_num % base;
40 rem_stack.push(rem);
41 dec_num /= base;
42 }
43
44 // 余数出栈并取对应字符来拼接成字符串
45 let mut base_str = "".to_string();
46 while !rem_stack.is_empty() {
47 let rem = rem_stack.pop().unwrap() as usize;
48 base_str += &digits[rem].to_string();
49 }
50
51 base_str
52}
53
54fn main() {
55 let bin_str: String = base_converter(10, 2);

Callers 1

mainFunction · 0.70

Calls 4

pushMethod · 0.45
to_stringMethod · 0.45
is_emptyMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected