问题描述
我想知道是否有一种方法可以使用C ++中的char来表示浮点数。
I'm wondering if there is a way to represent a float using a char in C++?
例如:
int main()
{
float test = 4.7567;
char result = charRepresentation(test);
return 0;
}
我读到可能使用bitset我可以做,但我不漂亮肯定。
I read that probably using bitset I can do it but I'm not pretty sure.
让我们假设我的float变量是01001010 01001010 01001010 01001010二进制。
Let's suppose that my float variable is 01001010 01001010 01001010 01001010 in binary.
char数组的4个元素,第一个元素将是01001010,第二个:01001010等。
If I want a char array of 4 elements, the first element will be 01001010, the second: 01001010 and so on.
我可以在4个元素的char数组中表示float变量吗?
Can I represent the float variable in a char array of 4 elements?
推荐答案
我怀疑你想说的是:
int main()
{
float test = 4.7567;
char result[sizeof(float)];
memcpy(result, &test, sizeof(test));
/* now result is storing the float,
but you can treat it as an array of
arbitrary chars
for example:
*/
for (int n = 0; n < sizeof(float); ++n)
printf("%x", result[n]);
return 0;
}
已编辑以添加:所有指出的人你不能适应 float
到8位当然是正确的,但实际上OP正在摸索的理解,一个 float
与所有原子数据类型一样,最终是一个简单的连续字节块。这对所有新手都不明显。
Edited to add: all the people pointing out that you can't fit a float
into 8 bits are of course correct, but actually the OP is groping towards the understanding that a float
, like all atomic datatypes, is ultimately a simple contiguous block of bytes. This is not obvious to all novices.
这篇关于在C ++中浮动到二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!