bcd-convert
A Rust library for working with Binary Coded Decimal (BCD) values. This crate provides utilities for converting between numeric types (such as u64) and BCD-encoded data, as well as parsing and formatting BCD values from and into strings.
Features
- BCD Parsing and Formatting: Convert BCD data into integers and vice versa.
- String Integration: Parse
BcdNumberfrom decimal strings and format them back. - Error Handling: Returns descriptive errors if invalid BCD data is encountered or if conversions overflow the target integer type.
- Standard Traits:
- Implements
FromStrandDisplayforBcdNumber, enabling"1234".parse::<BcdNumber>()andformat!()usage. - Implements
TryFrom/TryIntofor conversion to and fromu64.
- Implements
Example
use TryFrom;
use BcdNumber;
// From u64
let bcd_val = from_u64;
assert_eq!;
// To u64
let val = bcd_val.to_u64.unwrap;
assert_eq!;
// From string with leading zeros removed
let parsed = "0001234"..unwrap;
assert_eq!;
// Handling zero
assert_eq!;
assert_eq!;
// Understanding single-digit scenarios
// Here, 0x1 means the top nibble is 0 and the bottom nibble is 1, so "01"
let b = BcdNumber;
assert_eq!;
assert_eq!;
assert_eq!;
// Similarly, 0x01 means "01" as well.
let b = BcdNumber;
assert_eq!;
assert_eq!;
assert_eq!;
// From raw BCD bytes
let raw_bcd = &;
let from_bytes = try_from.unwrap;
assert_eq!;
// Error handling: invalid nibble
let invalid = &; // 0xA is not a valid BCD digit
assert!;
// Overflow check
let big_str = "999999999999999999999"; // Too large for u64
let big_num = big_str..unwrap;
assert!;
Installation
Add bcd-convert to your Cargo.toml:
[]
= "0.1.0"
Then run cargo build to fetch and build the library.
Documentation
Visit Docs.rs once the crate is published, or run cargo doc --open locally to view the generated documentation.
License
This project is licensed under the MIT License.