简体   繁体   English

C将char数组打印为float

[英]C printing char array as float

I'm trying to print a char array of 4 elements as a float number. 我正在尝试将4个元素的char数组打印为浮点数。 The compiler(gcc) won't allow me to write zs={'3','4','j','k'}; 编译器(gcc)不允许我写zs={'3','4','j','k'}; in the main() function, why? 在main()函数中,为什么?

#include <stdio.h>

union n{
    char s[4];
    float x;
};
typedef union n N;

int main(void)
{
    N z;
    z.s[0]='3';
    z.s[1]='4';
    z.s[2]='j';
    z.s[3]='k';
    printf("f=%f\n",z.x);
    return 0;
}

The output of the program above is: f=283135145630880207619489792.000000 , a number that is much larger than a float variable can store; 上面程序的输出是: f=283135145630880207619489792.000000 ,这个数字远远大于float变量可以存储的数字; the output should be, in scientific notation, 4.1977085E-8 . 输出应以科学计数法为4.1977085E-8 So what's wrong? 那有什么不对?

zs={'3','4','j','k'}; would assign one array to another. 将一个数组分配给另一个数组。 C doesn't permit that, though you could declare the second and memcpy to the first. C不允许这样做,尽管您可以将第二个和memcpy声明为第一个。

The largest finite value that a single-precision IEEE float can store is 3.4028234 × 10^38, so 283135145630880207619489792.000000, which is approximately 2.8313514 × 10^26 is most definitely in range. 单精度IEEE浮点型可以存储的最大有限值为3.4028234×10 ^ 38,因此283135145630880207619489792.000000 283135145630880207619489792.000000绝对在范围内,大约为2.8313514×10 ^ 26。

Assuming your chars are otherwise correct, the knee-jerk guess would be that you've got your endianness wrong. 假设您的字符是正确的,那么下意识的猜测就是您的字节序错了。

EDIT: 34jk if taken from left to right, as on a big-endian machine is: 编辑:34jk如果从左到右,如在大端机上是:

0x33 0x34 0x6a 0x6b
= 0011 0011, 0011 0100, 0110 1010, 0110 1011

So: 所以:

sign = 0
exponent = 011 0011 0 = 102 (dec), or -25 allowing for offset encoding
mantissa = [1] 011 0100 0110 1010 0110 1011 = 11823723 / (2^23)

So the value would be about 4.2 × 10^-8, which is what you want. 因此该值约为4.2×10 ^ -8,这就是您想要的。

In little endian: 在小尾数法中:

0x6b 0x6a 0x34 0x33 
= 0110 1011, 0110 1010, 0011 0100, 0011 0011

sign = 0
exponent = 110 1011 0 = 214 (dec) => 87
mantissa = [1]110 1010 0011 0100 0011 0011 = 15348787 / (2^23)

So the value would be about 2.8 * 10^26, which is what your program is outputting. 因此该值约为2.8 * 10 ^ 26,这是程序输出的结果。 It's a safe conclusion you're on a little endian machine. 这是一个安全的结论,说明您使用的是小型Endian计算机。

Summary then: byte order is different between machines. 总结:机器之间的字节顺序是不同的。 You want to use your bytes the other way around — try kj43 . 您想以其他方式使用字节—试试kj43

您实际看到的是{'k''j''4''3'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM