From 67cdcc2e12118becb823e20a40cc2687f2b8425a Mon Sep 17 00:00:00 2001 From: Adam Carpenter <53hornet@gmail.com> Date: Wed, 27 Mar 2019 15:32:37 -0400 Subject: Started Rust in Action MEAP. --- meap/meap-code/ch5/ch5-fixed-width.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 meap/meap-code/ch5/ch5-fixed-width.rs (limited to 'meap/meap-code/ch5/ch5-fixed-width.rs') diff --git a/meap/meap-code/ch5/ch5-fixed-width.rs b/meap/meap-code/ch5/ch5-fixed-width.rs new file mode 100644 index 0000000..fa0b867 --- /dev/null +++ b/meap/meap-code/ch5/ch5-fixed-width.rs @@ -0,0 +1,34 @@ +use num::{Float}; + +/// Q1_7 - single byte representation of a fixed point number with range [-1, 1]. +/// The name refers to the Texas Instrument representation +/// +/// References: +/// - English Wikipedia: "Q (number format)" https://en.wikipedia.org/wiki/Q_(number_format) +struct Q1_7(i8); // tuple struct holding a i8 value + +impl From for Q1_7 { + fn from (n:T) -> Self { + let val = if n > 1.0 { // out of bounds numbers are coerced to the maximum of the range + 1 + } else if n < -1.0 { + -1 + } else { + n * (2**7) + } + + Q1_7(val as i8) + } +} + +impl From for U: Float { + fn from(q: Q1_7) -> U { + q.0 * (2 ** -7) + } +} + +mod tests { + use super::*; + + test +} \ No newline at end of file -- cgit v1.2.3