读书人

C++函数HEX转换成ASCII码跪求帮忙!

发布时间: 2013-01-21 10:15:38 作者: rapoo

C++函数HEX转换成ASCII码,跪求帮忙!
本帖最后由 b104748590 于 2013-01-06 00:03:50 编辑 下面是我弄的函数,HEX转ASC的,但是我怎么弄都不对。

我是想实现这样的:假如现在有16进制的 20 20 20 33 35 30 2e 30 20 20 20 我想不处理20把中间5个16进制转换成ASCII码的话就应该等于350.0
20在ASCII里面应该是(space),每次读到20都有可能报错,郁闷死了!
float Rule::HexToAsc(unsigned char *Data)
{
long val=0;

val=Data[0] - 0x30;
val=Data[1] - 0x30;
val=Data[2] - 0x30;
val=Data[3] - 0x30;
val=Data[4] - 0x30;

return (float)val;
}

本人编程新手请大家帮帮忙。
c++ hex float 编程
[解决办法]
用这个,前面忘了释放内存了:


#include <string.h>
#include <stdlib.h>
#include <stdio.h>

float hex2asc(unsigned char* datas, int n)
{
float val;
char* str = (char*)malloc((n + 1) * sizeof(char));

memcpy(str, datas, n);
str[n] = '\0';
val = (float)atof(str);
free(str);

return val;
}

int main(int argc, char* argv[])
{
unsigned char datas[] = {0x20, 0x20, 0x20, 0x33, 0x35, 0x30, 0x2e, 0x30, 0x20, 0x20, 0x20};
printf("%f\n", hex2asc(datas, 11));

return 0;
}


[解决办法]

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static unsigned char asc2hex[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,


0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

char * strpack(const char *src, size_t len, char *dst)
{
unsigned char *from, *to, *end;

from = (unsigned char *)src;
to = (unsigned char *)dst;

for (end = to + len / 2; to < end; from += 2, to++)
*to = (asc2hex[*from] << 4)
[解决办法]
asc2hex[*(from + 1)];

return dst;
}

int main(int argc, char *argv[])
{
char src[] = "2020203335302e30202020";
char *dst;
int len;
double d;

len = strlen(src);
dst = malloc(len / 2 + 1);
dst[len / 2] = '\0';
strpack(src, len, dst);
d = atof(dst);

printf("[%s]\n", dst);
printf("[%f]\n", d);

return 0;
}

读书人网 >C++

热点推荐