如何将字符串转换成16进制的数据。

blandyzld 2010-03-18 11:48:19
例如将char型的字符串数组“1B52001B74131B52001B7413”转换成16进制的0x1B 0x52 0x00 0x1B 0x74 0x13等等,并存放到一个数组中。
...全文
833 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
happy_umust 2012-11-22
  • 打赏
  • 举报
回复
引用 6 楼 zhao4zhong1 的回复:
C/C++ code? 12345678910111213141516171819202122 #include <string.h> #include <stdio.h> #include <conio.h> #define MAX_BYTES 256 char str[] = "1B52001B74131B52001B7413"; unsigned char b[MAX_B……
大神啊~~~~
netimmortal 2012-02-19
  • 打赏
  • 举报
回复
用C关乎于机器
_JeffreyWu 2010-03-18
  • 打赏
  • 举报
回复

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
char str[] = "1B52001B74131B52001B7413";
vector<string> v;
string tmp = "0x";
for(int i=0; i<strlen(str); (tmp+=str[i],(i+2)%2 != 0)?(v.push_back(tmp),tmp="0x"):tmp,i++);
for (vector<string>::iterator iter = v.begin(); iter != v.end(); printf("%s\n",iter->c_str()) ,iter++);
return 0;
}
jixingzhong 2010-03-18
  • 打赏
  • 举报
回复
1. 对字符串进行填充,使用左补0方式,填充至字符串长度为偶数;
2. 循环,每次strncpy或memcpy两个字节的字符,使用sscanf或strtol转换为整形
toborac 2010-03-18
  • 打赏
  • 举报
回复
unsigned char _hex2dec(char h)
{
if(h >= 'A') {
h |= 0x20;
h -= 'a';
h += 10;
} else {
h -= '0';
}
return h;
}
unsigned char *convert_hex(char *input, int *output_len)
{
unsigned char *output, v;
int i,len;

len = strlen(input);
if(len % 2) {
return NULL;
}
output = (unsigned char*)malloc(len/2);
if(output == NULL) {
return NULL;
}
*output_len = len/2;
p = input;
for(i=0;i<len/2;i++) {
v = _hex2dec(*p++);
v <<= 4;
v ++ _hex2dec(*p++);
*output++ = v;
}
return output;
}
cy330206 2010-03-18
  • 打赏
  • 举报
回复
分段出来,再把分出来的数字放进相应的数组当中
pustian 2010-03-18
  • 打赏
  • 举报
回复
举个例子按照上面说的只要
算出字符串长,
然后确定出数组长,
读取每个字符,转换为一个整数
blandyzld 2010-03-18
  • 打赏
  • 举报
回复
谢谢各位已经解决了!
赵4老师 2010-03-18
  • 打赏
  • 举报
回复
#include <string.h>
#include <stdio.h>
#include <conio.h>
#define MAX_BYTES 256
char str[] = "1B52001B74131B52001B7413";
unsigned char b[MAX_BYTES];
int i,n;
void main() {
i=0;
while (1) {
if (1==sscanf(str+i*2,"%02x",b+i)) {
i++;
if (i>=MAX_BYTES) break;
} else {
break;
}
}
n=i;
for (i=0;i<n;i++) printf("%02X ",b[i]);
printf("\ntotal %d bytes.\n",n);
getch();
}

记不得哪位C++大牛在哪本学习C++的书的前言里面说过
“用C语言1000行源码能完成的工作千万不要用C++重写!”

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧