Skip to content

Commit 67459aa

Browse files
jdswensencfriedt
authored andcommitted
sys: util: add binary coded decimal functions
Some devices (such as RTCs) have data formats that expect BCD values instead of binary. These routines allow for converting between binary and BCD formats. Signed-off-by: Jake Swensen <[email protected]>
1 parent 8edcf02 commit 67459aa

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

include/sys/util.h

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,30 @@ size_t bin2hex(const uint8_t *buf, size_t buflen, char *hex, size_t hexlen);
285285
*/
286286
size_t hex2bin(const char *hex, size_t hexlen, uint8_t *buf, size_t buflen);
287287

288+
/**
289+
* @brief Convert a binary coded decimal (BCD 8421) value to binary.
290+
*
291+
* @param bcd BCD 8421 value to convert.
292+
*
293+
* @return Binary representation of input value.
294+
*/
295+
static inline uint8_t bcd2bin(uint8_t bcd)
296+
{
297+
return ((10 * (bcd >> 4)) + (bcd & 0x0F));
298+
}
299+
300+
/**
301+
* @brief Convert a binary value to binary coded decimal (BCD 8421).
302+
*
303+
* @param bin Binary value to convert.
304+
*
305+
* @return BCD 8421 representation of input value.
306+
*/
307+
static inline uint8_t bin2bcd(uint8_t bin)
308+
{
309+
return (((bin / 10) << 4) | (bin % 10));
310+
}
311+
288312
/**
289313
* @brief Convert a uint8_t into a decimal string representation.
290314
*

0 commit comments

Comments
 (0)