Last active
August 29, 2015 14:19
-
-
Save abonander/03d4c268368574a7c6b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!(""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment