浮点长度在32和40位之间变化 [英] Length of float changes between 32 and 40 bit

查看:171
本文介绍了浮点长度在32和40位之间变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将 float 值导出到文件时,遇到了一个奇怪的问题。我会期望每个浮点是相同的长度(显然),但我的程序有时导出一个32位数,有时作为一个40位数。
仍然显示此行为的程序的最小工作示例是:

I encountered an odd problem when exporting float values to a file. I would expect every float to be of the same length (obviously), but my programme sometimes exports it a 32 bit number and sometimes as a 40 bit number. A minimal working example of a programme that still shows this behaviour is:

#include <stdio.h>

const char* fileName = "C:/Users/Path/To/TestFile.txt";
float array [5];

int main(int argc, char* argv [])
{
    float temp1 = 1.63006e-33f;
    float temp2 = 1.55949e-32f;

    array[0] = temp1;
    array[1] = temp2;
    array[2] = temp1;
    array[3] = temp2;
    array[4] = temp2;

    FILE* outputFile;
    if (!fopen_s(&outputFile, fileName, "w")) 
    {
        fwrite(array, 5 * sizeof(float), 1, outputFile);
        fclose(outputFile);
    }

     return true;
}



我希望输出文件包含正好20(5乘4)字节,每四个表示一个浮点。但是,我得到这个:

I would expect the output file to contain exactly 20 (5 times 4) bytes, each four of which represent a float. However, I get this:

 8b 6b 07 09      // this is indeed 1.63006e-33f 
 5b f2 a1 0d 0a   // I don't know what this is but it's a byte too long
 8b 6b 07 09      
 5b f2 a1 0d 0a   
 5b f2 a1 0d 0a 

因此,float temp2 需要5个字节而不是4个字节,文件的长度是23.这是怎么可能的?数字不是那么小,它们是次正常数字,我不能想到任何其他原因为什么会有大小的差异。

So the float temp2 takes 5 bytes instead of four, and the total length of he file is 23. How is this possible?! The number aren't so small that they are subnormal numbers, and I can't think of any other reason why there would be a difference in size.

我使用在64位Windows 7系统上的MSVC 2010编译器。

I am using the MSVC 2010 compiler on a 64-bit Windows 7 system.

注意:我已经问过一个非常类似的问题,当我意识到问题更笼统,我决定以更简洁的方式转发它。
QDataStream有时使用32位,有时40位浮点数。

Note: I already asked a very similar question here, but when I realised the problem was more general, I decided to repost it in a more concise way. QDataStream uses sometimes 32 bit and sometimes 40 bit floats

推荐答案

问题是在Windows上,你必须区分文本和二进制文件。您已将文件打开为文本,这意味着 0d (回车)在每个 0a 饲料)。打开文件如下:

The problem is that on Windows, you have to differentiate between text and binary files. You have the file opened as text, which means 0d (carriage-return) is inserted before every 0a (line-feed) written. Open the file like this:

if (!fopen_s(&outputFile, fileName, "wb"))

剩下的就像以前一样工作。

The rest as before, and it should work.

这篇关于浮点长度在32和40位之间变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆