我需要一些帮助,将ASCII字符字符串转换为单个浮点数。我的数据有以下格式:
ìÀV3é¾V3»V3AÀV3ÁV3Û¶V3ÅV3=¾V3âºV3ðÂV3߸V3¿V3é¾V3ÁV3Û¶V3é¾V3ìÀV3ÁV3é¾V3ÁV3=¾V3DÂV3DÂV30¶V¿V3:¼V3¿V3ìÀV3,‘V3 V3·V3μAlV3
每四个字符应该表示一个浮点数。例如: 50.90101e-9;
我试图使用以下C++代码将此字符串转换为可读数据
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
int main (void)
{
int i;
int no_of_bytes;
char temp_string[2048];
float this_reading[100];
char *ptr;
no_of_bytes=32;
sprintf(temp_string,"%i",no_of_bytes*4);
/*convert char string to floating point*/
sprintf(temp_string,"%i","ìÀV3é¾V3»V3AÀV3ÁV3Û¶V3ÅV3=¾V3âºV3ðÂV3߸V3¿V3é¾V3ÁV3Û¶V3é¾V3ìÀV3ÁV3é¾V3ÁV3=¾V3DÂV3DÂV30¶V¿V3:¼V3¿V3ìÀV3,´V3¿V3·V3ìÀV3");
ptr=&temp_string [1];
/*convert char string to floating point*/
for(i=0; i<no_of_bytes; i++)
{
//puts(ptr);
this_reading [i] = *((float*)ptr);
ptr = ptr+4;
printf ("%e \n", this_reading [i]);
}
}
/*end of main*/但我得到了以下结果:
6.665629e-10
-6.321715e-30
4.056162e-02
-5.629500e+14
1.259217e-18
1.779649e-43
3.087247e+23
2.350968e-38
-2.437012e+01
9.439035e-38
0.000000e+00
-2.000000e+00
-nan
1.661560e+35
4.056162e-02
-5.629500e+14
1.259217e-18
1.779649e-43
3.096102e+23
2.350968e-38
-2.437012e+01
1.628646e+32
0.000000e+00
6.490371e+32
0.000000e+00
0.000000e+00
2.596148e+33
0.000000e+00
1.038459e+34
4.153837e+34
0.000000e+00
0.000000e+00我尝试使用一个浮点数,接近我想要转换的值,使用相同的方法将它转换为字符,然后返回到浮点数,结果中也有相同的错误:
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
int main (void)
{
float reading;
float number;
char *ptr;
float *pointer_number;
char temp_char ;
number = 50.90101e-9;
pointer_number = & number;
printf ("%e \n",*pointer_number);
temp_char = *((char*)pointer_number);
printf ("%c \n",temp_char);
ptr=&temp_char ;
puts(ptr);
reading = *((float*)ptr);
printf ("%f \n", reading);
}
/*end of main*/。
5.090101e-08
A
AA�Z3
22272396874481664.000000 我不是C/C++数据声明和操作方面的专家。我的最终目的是在Matlab中进行这种转换。我是从一种很老的仪器上读到这个价值的。他们在仪器手册中指定查询数据支持两种大小的数据类型,使用IEEE浮点算法标准(ANSI/IEEE Std )。754-1985年)。
谢谢!
发布于 2013-06-10 16:44:51
前10个值是
0 5.000122e-08
1 4.999939e-08
2 ?
3 5.000061e-08
4 ?
5 4.999206e-08
6 4.985647e-08
7 4.999878e-08
8 4.999573e-08
9 5.000305e-08
...您的50.90101e-9示例在我的4字节小endian浮点C计算机上转换为A � Z 3。由于Z 3类似于任何时候的第3,第4字符(几乎),它暗示您的字符串具有相同的小endian浮点格式。在C文件中放置字符串有两个问题。在我的C文件中,它转换了“μ¾V3éthe .”字符串到UTF8编码。通过联合使用浮标导致了混乱。您的字符串,如所示,肯定缺少一些字节。(我加了一些,以通过浮动#2。)我假设真正的字符串在文件中以其原始形式可用。以二进制方式打开该文件,并以float的形式一次读取该文件4个字节。
FILE *inf = fopen("Stringfilename", "rb");
int i = 0;
float f;
while (fread(&f, sizeof(f), 1, inf) == 1) {
printf("%d %e\n", i++, f);
}
fclose(inf);
printf("%d floats read.\n", i);发布于 2013-06-10 14:26:21
您的问题是temp_string包含垃圾。
sprintf(temp_string,"%i", string_literal)是错的。%i与字符指针不兼容,但是由于sprintf是一个varargs函数,编译器永远不知道您的类型不匹配。
失去sprintf,试着
const char* ptr = "...";然后你的循环就能工作了。
或者更简单:
const float *this_reading = (float*)"...";然后像数组一样使用它。
当然,所有这些代码都假设数据的字节顺序与C++平台相匹配。但是,如果你对数字运算更感兴趣,它应该“工作得很好”。
https://stackoverflow.com/questions/17025930
复制相似问题