一个C语言问题 字符串转十六进制保存在一个数组里 100
想把上述字符串存储在一个数组里,如下
a[] = { 0x01, 0x34,0x0e,0x0a,0x10,0xab,0xec );j
请高手快点解决一下,在线等 展开
//#include "stdafx.h"//vc++6.0加上这一行.
#include "stdio.h"
void main(void){
char Buffer[90]="01340E0A10ABEC",i,j;
unsigned char Hex[45],xh;
printf("Type a string...\nStr=");
scanf("%s",Buffer);
for(j=i=0;Buffer[i];i++){
Hex[j]=((xh=Buffer[i++])>'9' ? xh>='a' ? xh-0x57 : xh-0x37 : xh-'0')<<4;
Hex[j++] |= (xh=Buffer[i])>'9' ? xh>='a' ? xh-0x57 : xh-0x37 : xh-'0';
}
for(i=0;i<j;printf("0x%02X ",Hex[i++]));
printf("\n");
}
你可以使用骰memcpy来复制数组内容。
你说的跟我想要的结果根本不一样,按你说的话,我就不用问了。
#include "stdio.h"
#include "string.h"
#include "math.h"
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
// 0~9 48~57
// A~F 61~70
unsigned int hexToDec(char *str)
{
unsigned int i = 0;
unsigned int result = 0;
unsigned int tmp;
unsigned int len = strlen(str);
for(i = 0; i < len; i++)
{
if(str[i] >= 48 && str[i] <= 57)
{
tmp = str[i] - '0';
}
else if(str[i] >= 61 && str[i] <= 70)
{
tmp = str[i] - 'A' + 10;
}
else
{
printf("invalid hex %s\n",str);
return 0xFFFF;
}
result += tmp * pow(16,len-i-1);
}
return result;
}
int main()
{
char *input[] = {"01","34","0E","0A","10","AB","EC"};
int i = 0;
int result = 0;
int len = sizeof(input)/sizeof(char *);
for(i = 0; i < len; i++)
{
result = hexToDec(input[i]);
printf("%s in array is %x\n",input[i],result);
}
return 0;
}
输出:
01 in array is 1
34 in array is 34
0E in array is e
0A in array is a
10 in array is 10
AB in array is ab
EC in array is ec
亲 问你话呢~
unsigned char的数组
写个函数出来吧,我直接移进去 谢谢了
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void test(void)
{
char buffer[50] = "";
fgets(buffer,49,stdin);
int i = 0;
int len = (strlen(buffer)+1)/3;
char *a = (char *)malloc(len*5);//这里一个十六进制加一个逗号占五位
memset(a, '\0',len*5);
if(!a)
{
printf("error");
return;
}
for(i=0;i<len;i++)
{
strcat(a+i*5, "0x");
a[i*5+2] = buffer[i*3];
a[i*5+3] = buffer[i*3+1];
a[i*5+4] = ',';
}
a[i*5-1] = '\0';
puts(a);
}
int main(void)
{
test();
return 0;
}
//ok了,有问题再问我~没问题了就采纳了吧 ~ 谢谢~