Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::io::{self, Read, Write};
- fn xor(x: char, y: char) -> char {
- // Rust lacks the ternary operator.
- // Since if-blocks are expressions, it'd be redundant.
- if x != y { '1' } else { '0' }
- }
- fn or(x: char, y: char) -> char {
- if x == '1' || y == '1' { '1' } else { '0' }
- }
- fn and(x: char, y: char) -> char {
- if x == '1' { y } else { '0' }
- }
- /// Add the new bits together, returning the result and the carry out
- fn bit_adder(x: char, y: char, carry: char) -> (char, char) { // Eat my tuple, C
- let half_out = xor(x, y);
- let half_carry = and(x, y);
- let out = xor(half_out, carry);
- let carry = or(half_carry, and(half_out, carry));
- (out, carry)
- }
- fn adder(left: [char; 8], right: [char; 8]) -> [char; 8] {
- // Array initializer
- let mut out = ['0'; 8];
- let mut carry = '0';
- for i in (0 .. 8).rev() {
- let (new_out, new_carry) = bit_adder(left[i], right[i], carry);
- out[i] = new_out;
- carry = new_carry;
- }
- out
- }
- fn read_binary() -> [char; 8] {
- let mut stdin = io::stdin();
- let mut out = ['0'; 8];
- let mut buf = String::new();
- let _ = stdin.read_line(&mut buf).unwrap();
- for (ch, left_ch) in buf.trim().chars().zip(out.iter_mut()) {
- *left_ch = ch;
- }
- out
- }
- fn print_flush(st: &str) {
- print!("{}", st);
- io::stdout().flush().unwrap();
- }
- fn main() {
- print_flush("Enter the first number: ");
- let left = read_binary();
- print_flush("Enter the second number: ");
- let right = read_binary();
- let out = adder(left, right);
- print!("Result: ");
- for &ch in out.iter() {
- print!("{}", ch);
- }
- println!("");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement