1:目的
将BCD码转化成10进制数,并按照低位到高位的形式组合在一起。例如0x23和0x45 转化成 十进制4523
2:实现
/*******************************************************************************
* @file pow.c
* @verison v1.0.0
* @copyright COPYRIGHT © 2020 CSG
* @author ShiYanKai
* @date: 2021-07-03
* @brief
* @bug
* - 2021-07-03 SYK Created
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
unsigned char bcd_to_hex(unsigned char bcd)
{
if (((bcd & 0x0f) > 0x09) || ((bcd & 0xf0) > 0x90))
return 0;
return (bcd & 0x0f) + (bcd >> 4) * 10;
}
void bcd_to_hex_for_bytes(const void *p_src, void *p_dst, unsigned char size)
{
unsigned char i;
unsigned long long hex = 0;
unsigned char a;
for (i = size; i > 0; i--)
{
hex += (unsigned long long) bcd_to_hex(((unsigned char*) p_src)[i - 1]) * pow(10, 2 * (i - 1));
// double pow(double x, double y) 返回 x 的 y 次幂,即 xy。
}
memcpy((unsigned char*) p_dst, &hex, size);
}
int32_t DLT645_bcd_to_hex(uint8_t *p_src, uint8_t len, bool has_sign)
{
uint8_t sign = 0;
uint32_t hex = 0;
if (has_sign == true)
{
if (p_src[len - 1] & 0x80)
{
sign = 1;
p_src[len - 1] &= ~0x80;
}
}
bcd_to_hex_for_bytes(p_src, &hex, len);
if (sign == 1)
return -hex;
else
return hex;
}
int main()
{
float f_tmp = 0;
unsigned char a[] = {0x23, 0x45};
f_tmp = DLT645_bcd_to_hex(a, 2, false);
printf("%f\n", f_tmp);
printf("%f\n", f_tmp * 0.1);
}
3:编译并执行
yankaishi@zx-dev:~/test$ gcc pow.c -lm
yankaishi@zx-dev:~/test$ ./a.out
4523.000000
452.300000