summaryrefslogtreecommitdiff
path: root/meap/meap-code/ch5/ch5-u8-to-mock-rand.rs
diff options
context:
space:
mode:
authorAdam Carpenter <53hornet@gmail.com>2019-03-27 15:32:37 -0400
committerAdam Carpenter <53hornet@gmail.com>2019-03-27 15:32:37 -0400
commit67cdcc2e12118becb823e20a40cc2687f2b8425a (patch)
treeed92c3234b89079e6d4cf36f5e80c5ffa79def48 /meap/meap-code/ch5/ch5-u8-to-mock-rand.rs
parente25482fca375d318a39c3b54db396b0db6e0b263 (diff)
downloadlearning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.tar.xz
learning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.zip
Started Rust in Action MEAP.
Diffstat (limited to 'meap/meap-code/ch5/ch5-u8-to-mock-rand.rs')
-rw-r--r--meap/meap-code/ch5/ch5-u8-to-mock-rand.rs17
1 files changed, 17 insertions, 0 deletions
diff --git a/meap/meap-code/ch5/ch5-u8-to-mock-rand.rs b/meap/meap-code/ch5/ch5-u8-to-mock-rand.rs
new file mode 100644
index 0000000..46ac91a
--- /dev/null
+++ b/meap/meap-code/ch5/ch5-u8-to-mock-rand.rs
@@ -0,0 +1,17 @@
+// fn mock_rand(n: u8) -> f32 {
+// (n as f32) / 255.
+// }
+
+fn mock_rand(n: u8) -> f32 {
+ let base: u32 = 0b0_01111110_00000000000000000000000; // <1> Underscores mark the sign/mantissa/exponent boundaries
+ let large_n = (n as u32) << 15; // <2> Align the input byte `n` to 32 bits, then increase its value by shifting its bits 15 places to the left
+ let f32_bits = base | large_n; // <3> Take a bitwise OR, merging the base with the input byte
+ let m = f32::from_bits(f32_bits);// <4> Interpret `f32_bits` (which is type `u32`) as an `f32`
+ 2.0 * ( m - 0.5 ) // <5> Normalize the output range
+}
+
+fn main() {
+ println!("max of input range: {:08b} -> {}", 0xff, mock_rand(0xff));
+ println!("mid of input range: {:08b} -> {}", 0x77, mock_rand(0x77));
+ println!("min of input range: {:08b} -> {}", 0x00, mock_rand(0x00));
+} \ No newline at end of file