-
-
Save auroranockert/5733166 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
macro_rules! Q(($M:ident, $T:ident, $S:ty, $L:ty, $Q:expr) => (mod $M { | |
pub struct $T { value: $S } | |
static K:$L = 1 << ($Q - 1); | |
impl $T { | |
pub fn init(value: $S) -> $T { | |
$T { value: value } | |
} | |
pub fn to_s(&self) -> ~str { | |
fmt!("%?", (self.value as float) / ($Q as float).exp2()) | |
} | |
} | |
impl Neg<$T> for $T { | |
fn neg(&self) -> $T { | |
$T { value: -self.value } | |
} | |
} | |
impl Add<$T, $T> for $T { | |
fn add(&self, rhs: &$T) -> $T { | |
$T { value: self.value + rhs.value } | |
} | |
} | |
impl Sub<$T, $T> for $T { | |
fn sub(&self, rhs: &$T) -> $T { | |
$T { value: self.value - rhs.value } | |
} | |
} | |
impl Mul<$T, $T> for $T { | |
fn mul(&self, rhs: &$T) -> $T { | |
$T { value: (((self.value as $L) * (rhs.value as $L) + K) >> $Q) as $S } | |
} | |
} | |
impl Div<$T, $T> for $T { | |
fn div(&self, rhs: &$T) -> $T { | |
$T { value: ((((self.value as $L) << $Q) + ((rhs.value as $L) / 2)) / (rhs.value as $L)) as $S } | |
} | |
} | |
})) | |
Q!(FixedPoint, Q7, i8, i16, 7) | |
fn main() { | |
let a = FixedPoint::Q7::init(12); | |
let b = FixedPoint::Q7::init(-19); | |
io::println(fmt!("Add %s + %s = %s", a.to_s(), b.to_s(), (a + b).to_s())); | |
io::println(fmt!("Sub %s - %s = %s", a.to_s(), b.to_s(), (a - b).to_s())); | |
io::println(fmt!("Mul %s * %s = %s", a.to_s(), b.to_s(), (a * b).to_s())); | |
io::println(fmt!("Div %s / %s = %s", a.to_s(), b.to_s(), (a / b).to_s())); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment