将 float 转换为 char*

发布于 2024-09-05 07:16:35 字数 74 浏览 7 评论 0原文

如何使用 C 语言将 float 值转换为 char*

How can I convert a float value to char* in C language?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

醉南桥 2024-09-12 07:16:35
char buffer[64];
int ret = snprintf(buffer, sizeof buffer, "%f", myFloat);

if (ret < 0) {
    return EXIT_FAILURE;
}
if (ret >= sizeof buffer) {
    /* Result was truncated - resize the buffer and retry.
}

这会将 myFloat 的字符串表示形式存储在 myCharPointer 中。不过,请确保绳子足够大以容纳它。

snprintf 是比 sprintf 更好的选择,因为它保证它永远不会写入超过您在参数 2 中提供的缓冲区的大小。

char buffer[64];
int ret = snprintf(buffer, sizeof buffer, "%f", myFloat);

if (ret < 0) {
    return EXIT_FAILURE;
}
if (ret >= sizeof buffer) {
    /* Result was truncated - resize the buffer and retry.
}

That will store the string representation of myFloat in myCharPointer. Make sure that the string is large enough to hold it, though.

snprintf is a better option than sprintf as it guarantees it will never write past the size of the buffer you supply in argument 2.

阿楠 2024-09-12 07:16:35

在阿杜诺中:

//temporarily holds data from vals
char charVal[10];                

//4 is mininum width, 3 is precision; float value is copied onto buff
dtostrf(123.234, 4, 3, charVal);

monitor.print("charVal: ");
monitor.println(charVal);

In Arduino:

//temporarily holds data from vals
char charVal[10];                

//4 is mininum width, 3 is precision; float value is copied onto buff
dtostrf(123.234, 4, 3, charVal);

monitor.print("charVal: ");
monitor.println(charVal);
终难愈 2024-09-12 07:16:35
char array[10];
sprintf(array, "%f", 3.123);

sprintf:(来自 MSDN)

char array[10];
sprintf(array, "%f", 3.123);

sprintf: (from MSDN)

中二柚 2024-09-12 07:16:35

接受答案后很久。

使用 sprintf() 或相关函数,正如许多其他人建议的答案一样,但使用更好的格式说明符。

使用 "%.*e",代码解决了各种问题:

  • 使用 "%.*e" 所需的最大缓冲区大小更为合理,例如 18 浮动(见下文)。对于 "%f"(认为定点),sprintf(buf, "%f", FLT_MAX); 可能需要 47+ 字符sprintf(buf, "%f", DBL_MAX); 可能需要 317+ char

  • 使用".*"允许代码定义区分float x的字符串版本和它的下一个最大float所需的小数位数代码>.有关详细信息,请参阅 printf 宽度说明符以保持浮动精度- 点值

  • 使用"%e"允许代码区分小浮点数,而不是全部打印"0.000000"< /code> 这是 |x| 时的结果< 0.0000005“%f”


用法示例:

#include <float.h>
#define FLT_STRING_SIZE (1+1+1+(FLT_DECIMAL_DIG-1)+1+1+ 4   +1)
                     //  - d .  dddddddd           e - dddd \0

char buf[FLT_STRING_SIZE];
sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);

想法:
IMO,最好对暂存器使用 2 倍缓冲区大小,例如 buf[FLT_STRING_SIZE*2]
为了增强鲁棒性,请使用 snprintf()


作为第二种选择,请考虑“%.*g”。对于指数接近 1.0 的值,它类似于 "%f";对于其他值,类似于 "%e"

Long after accept answer.

Use sprintf(), or related functions, as many others have answers suggested, but use a better format specifier.

Using "%.*e", code solves various issues:

  • The maximum buffer size needed is far more reasonable with "%.*e", like 18 for float (see below). With "%f", (think fixed-point), sprintf(buf, "%f", FLT_MAX); could need 47+ char. sprintf(buf, "%f", DBL_MAX); may need 317+ char.

  • Using ".*" allows code to define the number of decimal places needed to distinguish a string version of float x and it next highest float. For details, see printf width specifier to maintain precision of floating-point value

  • Using "%e" allows code to distinguish small floats from each other rather than all printing "0.000000" which is the result when |x| < 0.0000005 with "%f".

Example usage:

#include <float.h>
#define FLT_STRING_SIZE (1+1+1+(FLT_DECIMAL_DIG-1)+1+1+ 4   +1)
                     //  - d .  dddddddd           e - dddd \0

char buf[FLT_STRING_SIZE];
sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);

Ideas:
IMO, better to use 2x buffer size for scratch pads like buf[FLT_STRING_SIZE*2].
For added robustness, use snprintf().


As a 2nd alterative consider "%.*g". It is like "%f" for values exponentially near 1.0 and like "%e" for others.

三五鸿雁 2024-09-12 07:16:35
char* str=NULL;
int len = asprintf(&str, "%g", float_var);
if (len == -1)
  fprintf(stderr, "Error converting float: %m\n");
else
  printf("float is %s\n", str);
free(str);
char* str=NULL;
int len = asprintf(&str, "%g", float_var);
if (len == -1)
  fprintf(stderr, "Error converting float: %m\n");
else
  printf("float is %s\n", str);
free(str);
莫相离 2024-09-12 07:16:35
typedef union{
    float a;
    char b[4];
} my_union_t;

您可以逐字节访问浮点数据值,并将其通过 8 位输出缓冲区(例如 USART)发送,而无需进行转换。

typedef union{
    float a;
    char b[4];
} my_union_t;

You can access to float data value byte by byte and send it through 8-bit output buffer (e.g. USART) without casting.

酒废 2024-09-12 07:16:35
char array[10];
snprintf(array, sizeof(array), "%f", 3.333333);
char array[10];
snprintf(array, sizeof(array), "%f", 3.333333);
故事未完 2024-09-12 07:16:35
// float arr to bytes
int arr_len = 3;
float x[3] = {1.123, 2.123, 3.123};
char* bytes = new char[arr_len * sizeof(float)];
memcpy(bytes, x, arr_len * sizeof(float));

// bytes to float arr
float y[3];
memcpy(y, bytes, arr_len * sizeof(float));
// float arr to bytes
int arr_len = 3;
float x[3] = {1.123, 2.123, 3.123};
char* bytes = new char[arr_len * sizeof(float)];
memcpy(bytes, x, arr_len * sizeof(float));

// bytes to float arr
float y[3];
memcpy(y, bytes, arr_len * sizeof(float));
墟烟 2024-09-12 07:16:35

通过 ascii 代码将浮点数转换为二进制

float u = 2.154328
string s = to_string(u);
char* p = (char*) s;

这存储字符 2, .,1, 5, ...,
或二进制
00000010,00101110, 00000001, ...

Convert float to binary via ascii codes

float u = 2.154328
string s = to_string(u);
char* p = (char*) s;

This stores the characters, 2, .,1, 5, ...,
or in binary
00000010,00101110, 00000001, ...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文