/**
* @brief 将两位数的十进制数(decimal)转换为 BCD格式。
* @param value: Byte to be converted.
* @retval Converted byte
*/
uint8_t byteToBcd(uint8_t value)
{
uint8_t bcd_high = 0;
for(i = 0; i < 10; i++)
{
if(value >= 10)
{
bcd_high++;
value -= 10;
}
else
break;
}
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));
}