我正在尝试将以下 Python 代码翻译成 C++:
import struct
import binascii
inputstring = ("0000003F" "0000803F" "AD10753F" "00000080")
num_vals = 4
for i in range(num_vals):
rawhex = inputstring[i*8:(i*8)+8]
# <f for little endian float
val = struct.unpack("<f", binascii.unhexlify(rawhex))[0]
print val
# Output:
# 0.5
# 1.0
# 0.957285702229
# -0.0
因此,它读取 32 位的十六进制编码字符串,使用该unhexlify
方法将其转换为字节数组,并将其解释为 little-endian 浮点值。
以下几乎可以工作,但代码有点蹩脚(最后00000080
解析不正确):
#include <sstream>
#include <iostream>
int main()
{
// The hex-encoded string, and number of values are loaded from a file.
// The num_vals might be wrong, so some basic error checking is needed.
std::string inputstring = "0000003F" "0000803F" "AD10753F" "00000080";
int num_vals = 4;
std::istringstream ss(inputstring);
for(unsigned int i = 0; i < num_vals; ++i)
{
char rawhex[8];
// The ifdef is wrong. It is not the way to detect endianness (it's
// always defined)
#ifdef BIG_ENDIAN
rawhex[6] = ss.get();
rawhex[7] = ss.get();
rawhex[4] = ss.get();
rawhex[5] = ss.get();
rawhex[2] = ss.get();
rawhex[3] = ss.get();
rawhex[0] = ss.get();
rawhex[1] = ss.get();
#else
rawhex[0] = ss.get();
rawhex[1] = ss.get();
rawhex[2] = ss.get();
rawhex[3] = ss.get();
rawhex[4] = ss.get();
rawhex[5] = ss.get();
rawhex[6] = ss.get();
rawhex[7] = ss.get();
#endif
if(ss.good())
{
std::stringstream convert;
convert << std::hex << rawhex;
int32_t val;
convert >> val;
std::cerr << (*(float*)(&val)) << "\n";
}
else
{
std::ostringstream os;
os << "Not enough values in LUT data. Found " << i;
os << ". Expected " << num_vals;
std::cerr << os.str() << std::endl;
throw std::exception();
}
}
}
(在 OS X 10.7/gcc-4.2.1 上编译,带有一个简单的g++ blah.cpp
)
特别是,我想摆脱BIG_ENDIAN
宏的东西,因为我确信有更好的方法来做到这一点,正如这篇文章所讨论的那样。
很少有其他随机细节 - 我不能使用 Boost(项目的依赖关系太大)。该字符串通常包含 1536 (8 3 *3) 到 98304 个浮点值 (32 3 *3),最多 786432 (64 3 *3)
(edit2:添加了另一个值,00000080
== -0.0
)