'How to invert binary string and convert to decimal
I want to invert 12 bit long string representation of binary number and convert it to decimal.
let a_str = "110011110101";
let b_str = invert(a_str); // value should be "001100001010"
println!("{}", isize::from_str_radix(a_str, 2).unwrap()); // decimal is 3317
println!("{}", isize::from_str_radix(b_str, 2).unwrap()); // decimal should be 778
Solution 1:[1]
You can use the bitwise not operator ! and mask out the unwanted bits:
let a = isize::from_str_radix(a_str, 2).unwrap();
println!("{a}");
println!("{}", !a & (1isize << a_str.len()).wrapping_sub(1));
Or you can manipulate the string, but this is much more expensive (allocation and copy):
let b_str = a_str
.chars()
.map(|c| if c == '0' { '1' } else { '0' })
.collect::<String>();
println!("{}", isize::from_str_radix(a_str, 2).unwrap());
println!("{}", isize::from_str_radix(&b_str, 2).unwrap());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chayim Friedman |
