从文件中读取 4 个十六进制值并转换为浮点数
Reading in 4 hex values from file and converting to float
所以我一直在 java 中创建文件格式,但我知道我需要从 C++ 应用程序中读取该二进制文件。
二进制文件只包含大量由 4 个十六进制值表示的浮点数。
十六进制示例数据:
FF B6 DD 99 8D FF 39 61 0C 62 FF 42
, FF B6 DD 99
是一个浮点数, 8D FF 39 61
是一个浮点数等等...
如何一次读取文件中的 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();
试试这个:
ifstream inp_file("path", ios::binary);
//...
float my_float = 0.0f;
inp_file.read((char *) &my_float, sizeof(my_float));
这仅在您的平台具有与 Java 实现相同的浮点实现时才有效。
顺便说一下,在您的代码中:
char packetPart[3];
while (true)
{
fRead.read(packetPart, 4);
您正在将 4 个字符读取到 3 个字符容量的数组中。你应该问问自己,"where does the 4 character go?".
所以我一直在 java 中创建文件格式,但我知道我需要从 C++ 应用程序中读取该二进制文件。
二进制文件只包含大量由 4 个十六进制值表示的浮点数。
十六进制示例数据:
FF B6 DD 99 8D FF 39 61 0C 62 FF 42
, FF B6 DD 99
是一个浮点数, 8D FF 39 61
是一个浮点数等等...
如何一次读取文件中的 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();
试试这个:
ifstream inp_file("path", ios::binary);
//...
float my_float = 0.0f;
inp_file.read((char *) &my_float, sizeof(my_float));
这仅在您的平台具有与 Java 实现相同的浮点实现时才有效。
顺便说一下,在您的代码中:
char packetPart[3];
while (true)
{
fRead.read(packetPart, 4);
您正在将 4 个字符读取到 3 个字符容量的数组中。你应该问问自己,"where does the 4 character go?".