简体   繁体   English

从文件中读取4个十六进制值并转换为float

[英]Reading in 4 hex values from file and converting to float

So I have been creating a file format in java but know I need to read in that binary file in from a C++ application. 因此,我一直在用Java创建文件格式,但知道我需要从C ++应用程序中读取该二进制文件。

The binary file just contains a huge number of floating point numbers represented by 4 hex values. 二进制文件仅包含由4个十六进制值表示的大量浮点数。

Sample Data in hex: FF B6 DD 99 8D FF 39 61 0C 62 FF 42 , FF B6 DD 99 is a float, 8D FF 39 61 is a float and so on... 十六进制样本数据: FF B6 DD 99 8D FF 39 61 0C 62 FF 42FF B6 DD 99是浮点数, 8D FF 39 61是浮点数,依此类推...

How do i read in the file 4 hex values at a time and convert into a float? 如何一次读取文件4个十六进制值并转换为浮点数?

    std::fstream fRead;
    fRead.open("path");

    if (fRead.fail())
    {
        fRead.close();
    } 
    else 
    {
        char packetPart[3];

        while (true) 
        {
            fRead.read(packetPart, 4);
            //std::cout << std::hex << std::setw(2) << std::setfill('0') << int(packetPart[0]) << std::endl;
            //I was trying to display the hex value but it didn't work.
        }
    }

    fRead.close();

Try this: 尝试这个:

ifstream inp_file("path", ios::binary);
//...
float my_float = 0.0f;
inp_file.read((char *) &my_float, sizeof(my_float));

This will only work if your platform has the same floating point implementation as the Java implementation. 仅当您的平台具有与Java实现相同的浮点实现时,此方法才有效。

By the way, in your code: 顺便说一句,在您的代码中:

char packetPart[3];

while (true) 
{
    fRead.read(packetPart, 4);

You are reading 4 characters into a 3 character capacity array. 您正在将4个字符读入3个字符的容量数组。 You should ask yourself, "where does the 4 character go?". 您应该问自己:“第4个字符在哪里?”。

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

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