Created
March 2, 2026 20:34
-
-
Save computermouth/1e4e5a9c11a1dd6d4b5e34b113b37ce1 to your computer and use it in GitHub Desktop.
Rust f32 float fraction truncation
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
| fn f32_to_f28(x: f32) -> f32 { | |
| let mut bytes = x.to_be_bytes(); | |
| bytes[3] = bytes[3] & 0xF0; | |
| f32::from_be_bytes(bytes) | |
| } | |
| fn f32_to_f24(x: f32) -> f32 { | |
| let mut bytes = x.to_be_bytes(); | |
| bytes[3] = 0; | |
| f32::from_be_bytes(bytes) | |
| } | |
| fn f32_to_f20(x: f32) -> f32 { | |
| let mut bytes = x.to_be_bytes(); | |
| bytes[2] = bytes[2] & 0xF0; | |
| bytes[3] = 0; | |
| f32::from_be_bytes(bytes) | |
| } | |
| fn f32_to_f16(x: f32) -> f32 { | |
| let mut bytes = x.to_be_bytes(); | |
| bytes[2] = 0; | |
| bytes[3] = 0; | |
| f32::from_be_bytes(bytes) | |
| } | |
| fn f32_to_f12(x: f32) -> f32 { | |
| let mut bytes = x.to_be_bytes(); | |
| bytes[1] = bytes[1] & 0xF0; | |
| bytes[2] = 0; | |
| bytes[3] = 0; | |
| f32::from_be_bytes(bytes) | |
| } | |
| fn f32_to_f10(x: f32) -> f32 { | |
| let mut bytes = x.to_be_bytes(); | |
| bytes[1] = bytes[1] & 0x80; | |
| bytes[2] = 0; | |
| bytes[3] = 0; | |
| f32::from_be_bytes(bytes) | |
| } | |
| fn main() { | |
| let original = std::f32::consts::PI; | |
| let truncated_28 = f32_to_f28(original); | |
| let truncated_24 = f32_to_f24(original); | |
| let truncated_20 = f32_to_f20(original); | |
| let truncated_16 = f32_to_f16(original); | |
| let truncated_12 = f32_to_f12(original); | |
| let truncated_10 = f32_to_f10(original); | |
| println!("f32: {:#034b} | {:08X} => {}", original.to_bits(), original.to_bits(), original); | |
| println!("f28: {:#034b} | {:08X} => {}", truncated_28.to_bits(), truncated_28.to_bits(), truncated_28); | |
| println!("f24: {:#034b} | {:08X} => {}", truncated_24.to_bits(), truncated_24.to_bits(), truncated_24); | |
| println!("f20: {:#034b} | {:08X} => {}", truncated_20.to_bits(), truncated_20.to_bits(), truncated_20); | |
| println!("f16: {:#034b} | {:08X} => {}", truncated_16.to_bits(), truncated_16.to_bits(), truncated_16); | |
| println!("f12: {:#034b} | {:08X} => {}", truncated_12.to_bits(), truncated_12.to_bits(), truncated_12); | |
| println!("f10: {:#034b} | {:08X} => {}", truncated_10.to_bits(), truncated_10.to_bits(), truncated_10); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment