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