1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
pub fn dec2binaryfluff(mut decimal:i128, length:i32) -> String {
let mut ret = "".to_string();
if decimal == 0 {
return decimal.to_string();
} else {
let mut bits = String::new();
while decimal > 0 {
if decimal % 2 == 0 {
bits.push_str("0");
} else {
bits.push_str("1");
}
decimal /= 2;
}
ret = bits.chars().rev().collect::<String>().parse::<String>().unwrap();
}
let mut fluff = "".to_string();
for _ in ret.len()..length as usize {
fluff.push_str("0")
}
let ret_final = format!("{}{}", fluff, ret.to_string());
ret_final.to_string()
}
pub fn dec2binary(mut decimal:i128) -> String {
let mut ret = "".to_string();
if decimal == 0 {
return decimal.to_string();
} else {
let mut bits = String::new();
while decimal > 0 {
if decimal % 2 == 0 {
bits.push_str("0");
} else {
bits.push_str("1");
}
decimal /= 2;
}
ret = bits.chars().rev().collect::<String>().parse::<String>().unwrap();
}
ret.to_string()
}
pub fn binary_str2dec(mut bin:String) -> i128 {
let mut decimal:f64 = 0 as f64;
for char in 0..bin.chars().count(){
if bin.as_bytes()[char] as char == '1'{
let expo:f64 = (bin.chars().count() - char - 1) as f64;
decimal+= (2 as f64).powi(expo as f64 as i32);
}
}
return decimal as i128;
}
pub fn binary_str2dec_str(mut bin:String) -> String {
let mut decimal:f64 = 0 as f64;
for char in 0..bin.chars().count(){
if bin.as_bytes()[char] as char == '1'{
let expo:f64 = (bin.chars().count() - char - 1) as f64;
decimal+= (2 as f64).powi(expo as f64 as i32);
}
}
return decimal.to_string();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn str_2_dec() {
let result = binary_str2dec("101".to_string());
assert_eq!(result, 5);
}
#[test]
fn str_2_dec_str() {
let result = binary_str2dec_str("00101".to_string());
assert_eq!(result, "5");
}
#[test]
fn dec_2_binary_string_fluff() {
let result = dec2binaryfluff(10,7);
assert_eq!(result, "0001010");
}
#[test]
fn dec_2_binary_string() {
let result = dec2binary(10);
assert_eq!(result, "1010");
}
}