BCD与ASCII码互转-C语言实现
来源:互联网 发布:linux touch 编辑:程序博客网 时间:2024/05/16 23:51
最近由于项目需要,需要将BCD编码转换为对应的字符串,下面为C语言实现,经测试好用!
转载请标明出处!
/*BCD 与 ASCII码转换*//*******************************************************************函数名: asc2bcd 功能描述:将ascii码转换为bcd码参数: bcd:转换后的BCD码 asc:需转换的ASCII码串 len:需转换的ascii码串长度返回值: uint32 0:成功 其他:失败********************************************************************/uint32 asc2bcd(uint8* bcd, const uint8* asc, uint32 len);/*******************************************************************函数名: bcd2asc 功能描述:将bcd码转换为ascii码串参数: asc:转换的ASCII码串 bcd:需转换的BCD码 len:需转换的BCD码长度返回值: uint32 0:成功 其他:失败********************************************************************/uint32 bcd2asc(uint8* asc, const uint8* bcd, uint32 len);
#include <assert.h>#include "utils.h"//基于查表实现BCD与Ascii之间的转换static uint8 bcd2ascii[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};static uint8 ascii2bcd1[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};static uint8 ascii2bcd2[6] = {0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
uint32 ASC2BCD(uint8 *bcd, const uint8 *asc, uint32 len){ uint8 c = 0; uint8 index = 0; uint8 i = 0; len >>= 1; for(; i < len; i++) { //first BCD if(*asc >= 'A' && *asc <= 'F') { index = *asc - 'A'; c = ascii2bcd2[index] << 4; } else if(*asc >= '0' && *asc <= '9') { index = *asc - '0'; c = ascii2bcd1[index] << 4; } asc++; //second BCD if(*asc >= 'A' && *asc <= 'F') { index = *asc - 'A'; c |= ascii2bcd2[index]; } else if(*asc >= '0' && *asc <= '9') { index = *asc - '0'; c |= ascii2bcd1[index]; } asc++; *bcd++ = c; } return 0;}
uint32BCD2ASC (uint8 *asc, const uint8 *bcd, uint32 len){ uint8 c = 0; uint8 i; for(i = 0; i < len; i++) { //first BCD c = *bcd >> 4; *asc++ = bcd2ascii[c]; //second c = *bcd & 0x0f; *asc++ = bcd2ascii[c]; bcd++; } return 0;}
int main(void)//测试程序{ const unsigned char ascii[12] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C'}; unsigned char bcd[6]; ASC2BCD(bcd, ascii, 12, 0); int i = 0; printf("ascii = %s\n", ascii); for(; i < 6; i++) { printf("bcd = 0x%.2x\n", bcd[i]); } /* unsigned char ascii[13] = {0}; const unsigned char bcd[6] = {0x01, 0x23, 0x45, 0xCD, 0xEF, 0xAB}; BCD2ASC(ascii, bcd, 6, 0); printf("ascii = %s\n", ascii); */ return 0;}
1 0
- BCD与ASCII码互转-C语言实现
- c语言实现十进制与ASCII码互转
- ASCII与BCD
- BCD码转十进制C语言实现
- c语言 ascii 和 压缩bcd 码之间的相互转换
- ASCII与BCD的理解,主要讲解BCD编码
- C语言之linux内核--BCD码转二进制与二进制转BCD码(笔试经典)
- Python Ascii to bcd bcd to Ascii
- BCD 转ASCII
- BCD HexString Ascii
- BCD ASCII 相互转换
- BCD,HEX,ASCII编码
- C语言ASCII字符集
- C语言编程实现打印HTML格式的ASCII表格
- 十六进制与ASCII码的互转(C语言)
- C语言--统计混合汉字与ASCII字符串字符数量
- BCD 互转 int ASCII 函数
- 【C语言基础】1-3 C语言关键字与ASCII码表
- 啊打发噶东方和苟富贵
- 阿道夫过哈哈大风歌
- C++ const修饰符的使用
- android viewPage
- 怎么在Ubuntu OS上面安装搜狗输入法及对Qt Creator的支持
- BCD与ASCII码互转-C语言实现
- Debug 集子
- brk()和sbrk()使用方法解析
- AutoLayout 自动布局
- ext4.0分页条件查询
- IOS开发之路
- JNI的一些工具函数
- PCB布线规范(华为)
- 搭建 Apache Http Server 服务器