求解一个c语言问题, 把字符转换位相应的十六进制数, 并存入一个字节中

#include<stdio.h>#include<stdlib.h>#include<string.h>charatohex(chars){charn=s;if(n>=... #include <stdio.h>
#include <stdlib.h>
#include <string.h>

char atohex(char s)
{
char n = s;

if( n >= 'a' && n <= 'z')
n = n + 'A' - 'a';

if(n > 0x39) //alpha
return (n - 0x37);
else //number
return (n - 0x30);
}

char chartohex(char *str)
{
char code[3], temp;
memset(code, 0, 3);
memcpy(code, str, 2);

temp = atohex(code[0]);
printf("the temp is %x\n", temp);
temp = (temp << 4) & 0xF0;
printf("the temp is %x\n", temp);
temp |= atohex(code[1]);
printf("the code is %s\n", code);

//printbinary(temp);
printf("the temp is %x, the sizeof(temp) is %d\n", temp, sizeof(temp));
return (char)temp;
}

int main()
{

char *pstr = "aB";
char c, z;

c = chartohex(pstr);
printf("The c hex is %x\n", c);
z = c;
printf("The c dec is %d\n", z);

}

我系统输出是:
the temp is a
the temp is ffffffa0 //按照设计,这应该是a0, 怎么多出6个f ???下面两个也是一样
the code is aB
the temp is ffffffab, the sizeof(temp) is 1
The c hex is ffffffab
The c dec is -85
展开
 我来答
谢应宸
2012-05-17 · TA获得超过2640个赞
知道大有可为答主
回答量:2731
采纳率:66%
帮助的人:2146万
展开全部
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char atohex(char s)
{
char n = s;

if( n >= 'a' && n <= 'z')
n = n + 'A' - 'a';

if(n > 0x39) //alpha
return (n - 0x37);
else //number
return (n - 0x30);
}

unsigned char chartohex(unsigned char *str)
{
unsigned char code[3];
unsigned char temp;
memset(code, 0, 3);
memcpy(code, str, 2);

temp = atohex(code[0]);
printf("the temp is %x\n", temp);
temp = (temp << 4) & 0xF0;
printf("the temp is %x\n", temp);
temp |= atohex(code[1]);
printf("the code is %s\n", code);

//printbinary(temp);
printf("the temp is %x, the sizeof(temp) is %d\n", temp, sizeof(temp));
return temp;
}

int main()
{

unsigned char pstr[] = "aB";
unsigned char c, z;

c = chartohex(pstr);
printf("The c hex is %x\n", c);
z = c;
printf("The c dec is %d\n", z);

return 0;
}
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式