gpt4 book ai didi

c - 如何将 char(ASCII 字符)转换为保存在 C 字符串变量中的科学计数法

转载 作者:行者123 更新时间:2023-11-30 21:05:50 25 4
gpt4 key购买 nike

各位同事,

我对下面复制的代码有疑问。我使用 StackOverflow 的一些用户提供的一些函数来完成我的代码(我不知道是否需要提及代码源),但我发现多次转换同一变量的效率非常低。

我从 ASCII 格式的文件中获取变量(4 个字节):

  42F00000 in hex (in ASCII you will see unprintable characters)

代码:

  //This code works in the main:
//
//I take out four bytes in ASCII format (from 0 to F representing
//hex characters) from a file and save them in the "temp4" variable.

arrayhexrcv[] comes from a file.

unsigned char temp4[3] = "";
unsigned long int tempul = 0ul;
float tempf = 0.0f;
char speed[12] = "";

temp4[0] = arrayhexrcv[0];
temp4[1] = arrayhexrcv[1];
temp4[2] = arrayhexrcv[2];
temp4[3] = arrayhexrcv[3];

//The first conversion is from ASCII to hex to obtain an hex string.
for(i=0;i<4;i++)
snprintf(temp4doble+(i*2), 9, "%02X", temp4[i]);
//2nd conversion is from hex to Unsigned Long Int.
tempul = strtoul(temp4doble, NULL, 16);
//3rd conversion is from Unsigned Long Int to Float.
tempf = UliAFloat(tempul);
//4th conversion is from Float to a string with the characters with
//value in scientific format.
snprintf(speed, 13, "%e", tempf);
printf("Speed in string of float is: %s\n, speed);

//UliAFloat function: This function converts Unsigned Long Int in Float.
#include<stdio.h>
float UliAFloat(unsigned long int x) {
union {
unsigned long int x;
float f;
} temp;
temp.x = x;
return temp.f;
}

最终,我在代表科学格式的字符串中获得了以下值:

1.200000e+02 (Speed in string format)

预先感谢您的帮助。

最佳答案

我不会重写这个,因为它效率低下;我会重写,因为它太复杂了。

此外,今天您似乎对 ASCII、十六进制和字节感到困惑。文件或内存中的字节是序列化的数据。一个值有时需要一个字节,有时需要更多;有时是固定数字,有时是可变数字。 (极少数情况下,一个值占用的空间少于一个字节。)当一个值占用的空间多于一个字节时,字节顺序(也称为字节顺序)很重要。 (ASCII 是文本的字符编码,与这里没有太大关系。)

十六进制有时是讨论一个字节或一组字节的值的一种方便的方式。在必须使用文本的情况下,表示任意字节值的一种方法是将字节转换为十六进制。

您似乎在文件中序列化了 float (IEEE-754 单精度 float )值。是32位的。理想情况下,读取该内容的方式是使用 fread)。但是,您将它放在一个数组中(大概是 char)。

我们在这里关注了很多实现定义的行为。假设CHAR_BITS == 8.) 因此,32 位需要 4 个字节。另外,假设浮点按小端顺序序列化,在本例中使用初始化数组,或者至少按照与从文件读取字节的机器中 native 的顺序相同的顺序。

char arrayhexrcv[4] = {0x00, 0x00, 0xF0, 0x42}; // little endian to match my machine

您只需获取 float 的地址并将其作为 float 访问即可:

printf("%e\n", *(float *)arrayhexrcv);

关于c - 如何将 char(ASCII 字符)转换为保存在 C 字符串变量中的科学计数法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52452559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com