首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

哪位高手解释上 这个函数中代码每一行的作用

2012-08-11 
谁解释下 这个函数中代码每一行的作用C/C++ code# define BYTEunsigned char# define UINT32 unsigned int

谁解释下 这个函数中代码每一行的作用

C/C++ code
# 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);}


[解决办法]
C/C++ code
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);}
[解决办法]
C/C++ code
#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。。

热点排行