Expand description
Binary-Coded Decimal (BCD) representation and conversion utilities.
This crate provides Bcd<BYTES>, a fixed-size, const-generic type for storing
unsigned integers in packed BCD format. Each byte holds two decimal digits, one
per nibble. The BYTES const parameter controls the storage size and therefore
the maximum representable value.
§BCD Format
In packed BCD, the value 1234 is stored as [0x12, 0x34]. The high nibble of
each byte holds the more-significant digit. Leading zero bytes are permitted and
are transparent to formatting and arithmetic conversions.
§Constructing a Bcd
There are three ways to build a Bcd:
Bcd::from_bcd_bytes— from a raw byte array already in BCD format.Bcd::try_from_u8and itstry_from_u16/try_from_u32/try_from_u64/try_from_u128/try_from_usizecounterparts — from a primitive integer via the double-dabble algorithm, returningBcdOverflowErroron overflow.- The
bcd!macro — a convenience wrapper that dispatches to the smallest primitive conversion capable of holding the value and panics on overflow.
Conversion back to primitives uses the matching try_into_* methods. For the
Bcd<BYTES> sizes that are guaranteed to fit in a target primitive, infallible
into_* methods are also provided.
§const support
All construction and conversion methods are const fn, and the bcd! macro
works in const context:
use const_bcd::{Bcd, bcd};
const N: Bcd<2> = bcd!(1234u16);§no_std
This crate is no_std compatible. The std feature is enabled by default but
has no functional effect — the crate uses only core internally. Disable it
for no_std targets:
[dependencies]
const-bcd = { version = "0.1", default-features = false }The crate never allocates, regardless of feature flags.
§Examples
use const_bcd::{Bcd, bcd};
// Construct from a primitive integer
let n: Bcd<2> = Bcd::try_from_u16(1234).unwrap();
assert_eq!(n.to_string(), "1234");
// Construct directly from raw BCD bytes
let n: Bcd<2> = Bcd::from_bcd_bytes([0x12, 0x34]).unwrap();
assert_eq!(n.to_string(), "1234");
// Convenience macro
let n: Bcd<2> = bcd!(1234u16);
assert_eq!(n.to_string(), "1234");
// Convert back to a primitive
let value: u16 = n.try_into_u16().unwrap();
assert_eq!(value, 1234);Macros§
Structs§
- Bcd
- A packed Binary-Coded Decimal (BCD) value backed by
BYTESbytes. - BcdOverflow
Error - Error returned when a conversion between an integer and a BCD overflows.
- Invalid
BcdDigit - Error returned when a byte contains a nibble with a value greater than 9.