Advertisement
Guest User

Untitled

a guest
May 25th, 2015
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. use std::io::{self, Read, Write};
  2.  
  3. fn xor(x: char, y: char) -> char {
  4. // Rust lacks the ternary operator.
  5. // Since if-blocks are expressions, it'd be redundant.
  6. if x != y { '1' } else { '0' }
  7. }
  8.  
  9. fn or(x: char, y: char) -> char {
  10. if x == '1' || y == '1' { '1' } else { '0' }
  11. }
  12.  
  13. fn and(x: char, y: char) -> char {
  14. if x == '1' { y } else { '0' }
  15. }
  16.  
  17. /// Add the new bits together, returning the result and the carry out
  18. fn bit_adder(x: char, y: char, carry: char) -> (char, char) { // Eat my tuple, C
  19. let half_out = xor(x, y);
  20. let half_carry = and(x, y);
  21. let out = xor(half_out, carry);
  22. let carry = or(half_carry, and(half_out, carry));
  23.  
  24. (out, carry)
  25. }
  26.  
  27. fn adder(left: [char; 8], right: [char; 8]) -> [char; 8] {
  28. // Array initializer
  29. let mut out = ['0'; 8];
  30. let mut carry = '0';
  31.  
  32. for i in (0 .. 8).rev() {
  33. let (new_out, new_carry) = bit_adder(left[i], right[i], carry);
  34. out[i] = new_out;
  35. carry = new_carry;
  36. }
  37.  
  38. out
  39. }
  40.  
  41. fn read_binary() -> [char; 8] {
  42. let mut stdin = io::stdin();
  43.  
  44. let mut out = ['0'; 8];
  45. let mut buf = String::new();
  46.  
  47. let _ = stdin.read_line(&mut buf).unwrap();
  48.  
  49. for (ch, left_ch) in buf.trim().chars().zip(out.iter_mut()) {
  50. *left_ch = ch;
  51. }
  52.  
  53. out
  54. }
  55.  
  56. fn print_flush(st: &str) {
  57. print!("{}", st);
  58. io::stdout().flush().unwrap();
  59. }
  60.  
  61.  
  62. fn main() {
  63. print_flush("Enter the first number: ");
  64. let left = read_binary();
  65.  
  66. print_flush("Enter the second number: ");
  67. let right = read_binary();
  68.  
  69. let out = adder(left, right);
  70.  
  71. print!("Result: ");
  72.  
  73. for &ch in out.iter() {
  74. print!("{}", ch);
  75. }
  76.  
  77. println!("");
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement