读书人

怎么将字符串转换成16进制的数据

发布时间: 2012-03-22 17:43:57 作者: rapoo

如何将字符串转换成16进制的数据。
例如将char型的字符串数组“1B52001B74131B52001B7413”转换成16进制的0x1B 0x52 0x00 0x1B 0x74 0x13等等,并存放到一个数组中。

[解决办法]
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;
}
[解决办法]

C/C++ code
#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;}
[解决办法]
C/C++ code
#include <string.h>#include <stdio.h>#include <conio.h>#define MAX_BYTES 256char 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语言

热点推荐