谁解释下 这个函数中代码每一行的作用
# define BYTE unsigned char# define UINT32 unsigned intBYTE hex2byte(char *buf, int offset) { UINT32 tmp; char *e; char buf2[3]; memcpy(buf2, &buf[offset], 2); buf[2] = 0; tmp = strtol(buf2, &e, 16); return (BYTE) (0xFF & tmp);}unsigned char hex2byte(char *hex_str, int offset) { // hex字符 转换成 unsigned int unsigned int tmp; char *e; char buf2[3]; // 缓冲 memcpy(buf2, &hex_str[offset], 2); // 把hex_str放到缓冲区 hex_str[2] = 0; tmp = strtol(buf2, &e, 16); // 字符转成 long 类型,后 return (unsigned char) (0xFF & tmp);}
[解决办法]
#include <stdio.h>#include <stdlib.h>#include <string.h>unsigned char hex2byte(char* hex_str, int offset) // hex字符 转换成 unsigned int{ unsigned int tmp; char* e; char buf2[3]; // 缓冲 memcpy(buf2, &hex_str[offset], 2); // 把hex_str 偏移量处的字符 放到缓冲区 hex_str[2] = 0; tmp = strtol(buf2, &e, 16); // 字符转成 long 类型,后 return (unsigned char)(0xFF & tmp);}int main(){ char hex_str[] = "add:646464"; printf("%c%c ->", hex_str[4], hex_str[5]); printf("%d", hex2byte(hex_str , 4)); // 输出 64 -> 100 return 0;}
[解决办法]
/*
16进制字节串转相应的值
比 "FF"->255 "12"->18
实现:
程序主要借助strtol函数把16进制串
转换成相应的值
另外用sscanf函数更简单
*/
#define BYTE unsigned char
#define UINT32 unsigned int
BYTE hex2byte(char *buf, int offset) {
UINT32 tmp;
char *e;
char buf2[3];
memcpy(buf2, &buf[offset], 2);
buf[2] = 0;//程序BUG应为buf2[2]=0
tmp = strtol(buf2,&e, 16);
return (BYTE) (0xFF & tmp);
}
int main(void)
{
char *hexstr = "ff";
unsigned char ch;
sscanf(hexstr,"%x",&ch);
printf("%d-%d\n",hex2byte("ff",0),ch);
return 0;
}
[解决办法]
memmove。。