Skip to content

Instantly share code, notes, and snippets.

@jkilpatr
Created July 31, 2017 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkilpatr/19bb17d9ec03bd3a2a0e0dbd1e029221 to your computer and use it in GitHub Desktop.
Save jkilpatr/19bb17d9ec03bd3a2a0e0dbd1e029221 to your computer and use it in GitHub Desktop.
extern crate bit_vec;
use bit_vec::BitVec;
use std::ops::Add;
use std::ops::Sub;
fn twos_comp(mut bv: BitVec) {
let mut one = BitVec::from_elem(bv.len(), false);
one.set(0) = true;
bv.negate();
bv = bv_add(bv, one);
bv;
}
fn assign(mut bv: BitVec, other: i32) {
let neg = other < 0;
let other = other.abs();
let mut to_add = other;
let mut pow = 256;
while pow >= 0 {
if 2^pow < other {
to_add = to_add - 2^pow;
bv.set(pow, true);
}
}
if neg {
bv.twos_comp();
}
bv;
}
fn bv_add(bv: BitVec, other: BitVec) {
assert_eq!(bv.len(), other.len());
let mut bit = 0;
let mut carry = false;
while bit < bv.len() {
if bv.get(bit) == Some(true)
&& other.get(bit) == Some(true)
&& carry == Some(true) {
bv.set(bit) = true;
carry = true;
}
else if bv.get(bit) == Some(false)
&& other.get(bit) == Some(true)
&& carry == Some(true) {
bv.set(bit) = false;
carry = true;
}
else if bv.get(bit) == Some(true)
&& other.get(bit) == Some(false)
&& carry == Some(true) {
bv.set(bit) = false;
carry = true;
}
else if bv.get(bit) == Some(false)
&& other.get(bit) == Some(false)
&& carry == Some(true) {
bv.set(bit) = true;
carry = false;
}
else if bv.get(bit) == Some(true)
&& other.get(bit) == Some(false)
&& carry == Some(false) {
bv.set(bit) = true;
carry = false;
}
else if bv.get(bit) == Some(false)
&& other.get(bit) == Some(true)
&& carry == Some(false) {
bv.set(bit) = true;
carry = false;
}
bit = bit + 1;
}
bv;
}
// Two's compliment subtraction is the same
// as the addition operation
fn Sub(mut bv: BitVec, other: BitVec) {
bv = bv_add(bv,other);
bv;
}
fn main() {
println!("Hello, world!");
let test = BitVec::(256,Some(false));
let test = assign(test, -24)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment