Skip to content

Commit

Permalink
Add mantissa_from convenience method.
Browse files Browse the repository at this point in the history
  • Loading branch information
rpitasky committed Aug 3, 2023
1 parent 2cd4812 commit 26bc8c3
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "tifloats"
version = "2.0.0"
version = "2.1.0"
edition = "2021"
license = "MIT OR Apache-2.0"
homepage = "https://github.com/TI-Toolkit/tifloats_lib_rs"
Expand Down
35 changes: 35 additions & 0 deletions src/float.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,25 @@ impl Float {
}
}

/// Convenience method to produce the appropriate packed-BCD mantissa from a
/// sequence of decimal digits, read from left to right (MSD = `digits[0]`).
pub fn mantissa_from(digits: &[u8]) -> u64 {
let digits = Vec::from(digits);

let dec = digits
.iter()
.take(14)
.enumerate()
.map(|(index, &value)| -> u64 { (1 << (4 * (13 - index as u64))) * value as u64 })
.sum::<u64>();

if digits.len() >= 15 && digits[14] >= 5 {
(Mantissa::from(dec).unwrap() + Mantissa::ULP).bits()
} else {
dec
}
}

/// Given a Float, produces byte representation (flags at index zero).
pub fn to_raw_bytes(&self) -> [u8; 9] {
let mut result = vec![self.flags.bits, self.exponent];
Expand Down Expand Up @@ -313,4 +332,20 @@ mod tests {
assert_eq!(float.to_raw_bytes(), repr);
assert_eq!(Float::from_raw_bytes(repr).ok().unwrap(), float);
}

#[test]
fn mantissa_from() {
let cases = [
(vec![5], 0x50000000000000_u64),
(vec![1, 2, 3, 4, 5, 6, 7, 8, 9], 0x12345678900000),
(
vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 9, 9],
0x12345678901240,
),
];

for (digits, expected) in cases {
assert_eq!(Float::mantissa_from(&digits), expected);
}
}
}

0 comments on commit 26bc8c3

Please sign in to comment.