4G_module/custom/jt808/src/jt808_util.c

94 lines
2.0 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "jt808_util.h"
#include "jt808_config.h"
// 双字节大小端转换
uint16_t Swap16(uint16_t val16){
return (((val16 & 0x00FF) << 8) |
((val16 & 0xFF00) >> 8));
}
// 四字节大小端转换
uint32_t Swap32(uint32_t val32){
return (((val32 & 0x000000FF) << 24) |
((val32 & 0x0000FF00) << 8) |
((val32 & 0x00FF0000) >> 8) |
((val32 & 0xFF000000) >> 24));
}
// 异或校验
uint8_t BCC_Check(const uint8_t *src, uint32_t len)
{
uint8_t bcc_check = 0;
for(uint32_t i = 0; i < len; ++i){
bcc_check ^= src[i];
}
return bcc_check;
}
// 十进制转BCD码
uint8_t DecToBcd(uint8_t Dec){
uint8_t temp;
temp = ((Dec / 10) << 4) + (Dec % 10);
return temp;
}
// BCD码转十进制
uint8_t BcdToDec(uint8_t Bcd){
uint8_t temp;
temp = (Bcd >> 4) * 10 + (Bcd & 0x0f);
return temp;
}
// 原始字符串转BCD码 //奇数位时首位BCD码前面补0
uint8_t *rawStrToBcd(uint8_t *bcd, const uint8_t *str, uint16_t str_len){
uint8_t *ptr = bcd;
uint8_t temp;
if (str_len % 2 != 0){
*ptr++ = DecToBcd(*str++ - '0');
}
while (*str){
temp = *str++ - '0';
temp *= 10;
temp += *str++ - '0';
*ptr++ = DecToBcd(temp);
}
return bcd;
}
// BCD转字符串自动去掉bcd码前导零
// bcdlen 为bcd码字节数
uint8_t *BcdToStr(uint8_t *str, const uint8_t *bcd, int bcd_len){
uint8_t *ptr = str;
uint8_t temp;
int cnt = bcd_len;
while (cnt--){
temp = BcdToDec(*bcd);
*ptr++ = temp / 10 + '0';
if(str[0] == '0'){
ptr = str;
}
*ptr++ = temp % 10 + '0';
if(str[0] == '0'){
ptr = str;
}
++bcd;
}
return str;
}
// 原始BCD数据转字符串
// strlen 为原始BCD数据字节数
uint8_t *rawBcdToStr(uint8_t *str, const uint8_t *bcd, int bcd_len){
uint8_t *ptr = str;
uint8_t temp;
int cnt = bcd_len;
while (cnt--)
{
temp = BcdToDec(*bcd);
*ptr++ = temp / 10 + '0';
*ptr++ = temp % 10 + '0';
++bcd;
}
return str;
}