C语言 如何将浮点数转换为 C 中的 4 字节字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18270974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a float to a 4 byte char in C?
提问by 12oni
I want to convert a float number for example 2.45 to the 4 byte char array.
so the 2.45 should look like this '@' 'FS' 'ì' 'í'which is binary the ieee representation of 2.45 = 01000000 00011100 11001100 11001101?
我想将浮点数(例如 2.45)转换为 4 字节字符数组。所以 2.45 应该是这样的 '@' 'FS' 'ì' 'í',它是二进制的 ieee 表示2.45 = 01000000 00011100 11001100 11001101?
I've solved the problem but it has a bad complexity. do you have any good ideas?
我已经解决了这个问题,但它的复杂性很差。你有什么好主意吗?
Thanks for the good answers.
谢谢你的好答案。
can you please tell me the way back from the char array to the float number ?
你能告诉我从字符数组到浮点数的方法吗?
回答by Paul R
Just use memcpy:
只需使用 memcpy:
#include <string.h>
float f = 2.45f;
char a[sizeof(float)];
memcpy(a, &f, sizeof(float));
If you require the opposite endianness then it is a trivial matter to reverse the bytes in aafterwards, e.g.
如果您需要相反的字节序,那么在a之后反转字节是一件小事,例如
int i, j;
for (i = 0, j = sizeof(float) - 1; i < j; ++i, --j)
{
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
回答by Some programmer dude
You have a few ways of doing this, including these two:
您有几种方法可以做到这一点,包括以下两种:
Use typecasting and pointers:
float f = 2.45; char *s = (char *) &f;Note that this isn't safe in any way and that there is no string terminator after the "string".
Use a
union:union u { float f; char s[sizeof float]; }; union u foo; foo.f = 2.45;The char array can now be accessed to get the byte values. Also note like the first alternative there is no string terminator.
使用类型转换和指针:
float f = 2.45; char *s = (char *) &f;请注意,这在任何方面都不安全,并且“字符串”之后没有字符串终止符。
使用
union:union u { float f; char s[sizeof float]; }; union u foo; foo.f = 2.45;现在可以访问 char 数组以获取字节值。另请注意,与第一个选择一样,没有字符串终止符。

