/**
* @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));
}