我已经下载了Dukascopy tick数据,我用easylzma库解压缩了它.原始压缩二进制文件是EURUSD / 2010/00/08 / 12h_ticks.bi5(EURUSD / 2010 / ian / 8 / 12h)解压后我们得到以下格式:
+-------------------------+--------+-------+ | time | Bid | Ask | +-------------------------+--------+-------+ 000003CA 00022EC0 00022EB6 40CCCCCD 41180000 000004F5 00022EB6 00022EB1 4099999A 404CCCCD
(您可以从以下位置下载原始压缩文件:
EURUSD/2010/00/08/12h_ticks.bi5.
用lzma解压缩后我们得到文件:
12h_ticks)
读取二进制文件:
int ii1; int ii2; int ii3; float ff1; float ff2; ifstream in("12h_ticks",ofstream::binary); in.read((char*)(&ii1),sizeof(int)); in.read((char*)(&ii2),sizeof(int)); in.read((char*)(&ii3),sizeof(int)); in.read((char*)(&ff1),sizeof(float)); in.read((char*)(&ff2),sizeof(float)); std::cout << " ii1=" << ii1 << std::endl; std::cout << " ii2=" << ii2 << std::endl; std::cout << " ii3=" << ii3 << std::endl; std::cout << " ff1=" << ff1 << std::endl; std::cout << " ff2=" << ff2 << std::endl; in.close();
我得到以下结果:
ii1=-905773056 ii2=-1070726656 ii3=-1238498816 ff1=-4.29492e+08 ff2=8.70066e-42
怎么了?我无法从二进制文件中读取数据.请帮我.
解决方法
数据似乎以大端格式存储在文件中.加载时,您需要将其转换为小端.
#include <iostream> #include <fstream> #include <algorithm> template<typename T> void ByteSwap(T* p) { for (int i = 0; i < sizeof(T)/2; ++i) std::swap( ((char *)p)[i],((char *)p)[sizeof(T)-1-i] ); } int main() { int ii1; int ii2; int ii3; float ff1; float ff2; std::ifstream in("12h_ticks",std::ofstream::binary); in.read((char*)(&ii1),sizeof(int)); in.read((char*)(&ii2),sizeof(int)); in.read((char*)(&ii3),sizeof(int)); in.read((char*)(&ff1),sizeof(float)); in.read((char*)(&ff2),sizeof(float)); ByteSwap(&ii1); ByteSwap(&ii2); ByteSwap(&ii3); ByteSwap(&ff1); ByteSwap(&ff2); std::cout << " ii1=" << ii1 << std::endl; std::cout << " ii2=" << ii2 << std::endl; std::cout << " ii3=" << ii3 << std::endl; std::cout << " ff1=" << ff1 << std::endl; std::cout << " ff2=" << ff2 << std::endl; in.close(); return 0; }
这给出了结果:
ii1=970 ii2=143040 ii3=143030 ff1=6.4 ff2=9.5
如果你想了解更多有关该主题的信息,我会从这里获取ByteSwap功能. How do I convert between big-endian and little-endian values in C++?