介绍一种将ASCII码字符串转换为二进制字节数据的方法

/** * @brief 该函数实现了将可打印ASCII码字符串转换为二进制字节数据 * @param[in] pSrc 源数据指针 * @param[out] pDst 目标字符串指针 * @param[in] nSrcLength 源数据长度 * @param[out] nDstLength 目标字符串长度 * @return 返回操作结果 * - 0 表示操作成功 * - -1 表示操作失败 * @author wlq_729@163.com * http://blog.csdn.net/rabbit729 * @version 1.0 * @date 2009-02-26 */ #include <ctype.h> #include <iostream> using namespace std; int hex2bin(const char* pSrc, unsigned char* pDst, unsigned int nSrcLength, unsigned int& nDstLength) { if ( (pSrc == 0) || (pDst == 0) ) { return -1; } nDstLength = 0; if ( pSrc[0] == 0 ) // nothing to convert return 0; // 计算需要转换的字节数 for ( int j = 0; pSrc[j]; j++ ) { if ( isxdigit(pSrc[j]) ) nDstLength++; } // 判断待转换字节数是否为奇数,然后加一 if ( nDstLength & 0x01 ) nDstLength++; nDstLength /= 2; if ( nDstLength > nSrcLength ) return -1; nDstLength = 0; int phase = 0; for ( int i = 0; pSrc[i]; i++ ) { if ( ! isxdigit(pSrc[i]) ) continue; unsigned char val = pSrc[i] - ( isdigit(pSrc[i]) ? 0x30 : ( isupper(pSrc[i]) ? 0x37 : 0x57 ) ); if ( phase == 0 ) { pDst[nDstLength] = val << 4; phase++; } else { pDst[nDstLength] |= val; phase = 0; nDstLength++; } } return 0; } void main(void) { char test[] = "23a4B7"; unsigned char result[4]; memset(result, 0, 4); unsigned int nResult = 0; hex2bin(test, result, 6, nResult); cout<<result<<endl; cout<<nResult<<endl; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值