/**
* @brief Converts a 2 digit decimal to BCD format.
* @param value: Byte to be converted.
* @retval Converted byte
*/
uint8_t byteToBcd(uint8_t value)
{
uint8_t bcd_high = 0;
while (value >= 10)
{
bcd_high++;
value -= 10;
}
return ((bcd_high << 4) | value);
}
以上代码参考ST的库函数,规避了除法的使用,因为编码规范上有要求:能用移位操作来实现的运算就不要使用除法来实现,提高代码的运行效率。
/**
* @brief Convert from 2 digit BCD to Binary.
* @param Value: BCD value to be converted.
* @retval Converted word
*/
uint8_t bcdToByte(uint8_t value)
{
return ((value >> 4) * 10 + (value & 0x0F));
}