计算器将二进制转换为浮点值 - 我做错了什么? [英] Calculator to convert binary to float value -- what am I doing wrong?

查看:221
本文介绍了计算器将二进制转换为浮点值 - 我做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,它以二进制形式将6个浮点数写入磁盘,并读取它们:

I have the following code, which writes 6 floats to disk in binary form and reads them back:

#include <iostream>
#include <cstdio>

int main()
{
  int numSegs = 2;
  int numVars = 3;

  float * data = new float[numSegs * numVars];
  for (int i = 0; i < numVars * numSegs; ++i) {
    data[i] = i * .23;
    std::cout << data[i] << std::endl;
  }

  FILE * handle = std::fopen("./sandbox.out", "wb");

  long elementsWritten = 
    std::fwrite(data, sizeof(float), numVars*numSegs, handle);

    if (elementsWritten != numVars*numSegs){
      std::cout << "Error" << std::endl;
    }

    fclose(handle);
    handle = fopen("./sandbox.out", "rb");

    float * read = new float[numSegs * numVars];

    fseek(handle, 0, SEEK_SET);

    fread(read, sizeof(float), numSegs*numVars, handle);

    for (int i = 0; i < numVars * numSegs; ++i) {
      std::cout << read[i] << std::endl;
    }
}

它输出:

0
0.23
0.46
0.69
0.92
1.15
0
0.23
0.46
0.69
0.92
1.15

当我加载文件在一个hexer,我们得到:

When I load the file in a hexer, we get:

00 00 00 00 1f 85 6b 3e  1f 85 eb 3e d7 a3 30 3f
1f 85 6b 3f 33 33 93 3f  -- -- -- -- -- -- -- --

我想直接从十进制计算浮点值。例如: 1f 85 6b 3e 变成0.23, 1f 85 eb 3e 变成0.46。

I want to be calculate the float value from the decimal directly. For example: 1f 85 6b 3e becomes 0.23 and 1f 85 eb 3e becomes 0.46.

我已经在网上尝试了一些二进制浮点计算器。当我把数字的十六进制表示, 0x1f856b3e ,在这两个计算器我回到5.650511E-20
。但我认为该值应该是0.23,因为我提供字节5-8到计算器,这些字节表示写入磁盘的第二个浮点。

I've tried a few "binary to float" calculators on the web. When I put in the hexadecimal representation of the number, 0x1f856b3e, in both calculators I get back 5.650511E-20 . But I thought the value should be 0.23 since I provided bytes 5-8 to the calculator and these bytes represent the second float written to disk.

我做错了什么?

推荐答案

a href =http://en.wikipedia.org/wiki/Endianness =nofollow> endianness 问题,如果您例如切换:

This is an endianness issue if you for example switch:

1f 85 6b 3e 

至:

3e 6b 85 1f

这将导致 .23 ,当你使用你的转换器转换它,例如我使用 IEEE 754转换器浮动指向Hex转换器允许您进行双精度转换和单精度转换。

this will result in .23 when you convert it using one of your converters, for example I used IEEE 754 Converter and Floating Point to Hex Converter allows you to do double as well as single precision conversions.

这篇关于计算器将二进制转换为浮点值 - 我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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