WinView SPE to TXT converter

id:flappphys:20080712#p1 の,もっとシンプルな版.
どうでもいいが cl.exe 15.00.21022.08 for 80x86 でこれを /O2 付きでコンパイルすると type の値がおかしい.読み取った直後は(例えば) 5 なのに,xLen とかと一緒に表示するところでは 0 になってしまう./O1 では 5 のまま.reinterpret_cast 辺りはともかくとして,static_cast とかSTL vector中の配列アクセスだけで最適化オプションにより結果が変わるっておかしくない?
(追記:以下はコメントに感謝しつつ修正した版)

#include <iostream>
#include <fstream>
#include <string>

#include <algorithm>
#include <vector>

using namespace std;

typedef unsigned char uchar;
typedef unsigned int uint;

typedef union {
    uint u[2];
    double d;
} du_t;

double readIEEE754Double(char *buf)
{
    du_t du;
    du.u[0] = (static_cast<uchar>(buf[3]) << 24) | (static_cast<uchar>(buf[2]) << 16)
        | (static_cast<uchar>(buf[1]) << 8) | static_cast<uchar>(buf[0]);
    du.u[1] = (static_cast<uchar>(buf[7]) << 24) | (static_cast<uchar>(buf[6]) << 16)
        | (static_cast<uchar>(buf[5]) << 8) | static_cast<uchar>(buf[4]);
    return du.d;
    /* double val;
    int *vp(reinterpret_cast<int*>(&val));
    *vp = (static_cast<uchar>(buf[3]) << 24) | (static_cast<uchar>(buf[2]) << 16)
        | (static_cast<uchar>(buf[1]) << 8) | static_cast<uchar>(buf[0]);
    *(vp+1) = (static_cast<uchar>(buf[7]) << 24) | (static_cast<uchar>(buf[6]) << 16)
        | (static_cast<uchar>(buf[5]) << 8) | static_cast<uchar>(buf[4]);
    return val; */
}

int main(int argc, char *argv[])
{
    ifstream ifs(argv[1], ios::binary);
    char *dot(".");
    char *dotPos(find_end(argv[1], argv[1] + strlen(argv[1]), dot, dot + 1));
    string oName(argv[1], dotPos);
    oName += ".txt";
    // cout << oName << endl;

    char buf[4];

    ifs.seekg(42);
    ifs.read(buf,3);
    uint xLen((static_cast<uchar>(buf[1]) << 8) | static_cast<uchar>(buf[0]));

    ifs.seekg(656);
    ifs.read(buf,2);
    uint yLen((static_cast<uchar>(buf[1]) << 8) | static_cast<uchar>(buf[0]));

    ifs.seekg(108);
    ifs.read(buf,1);
    uint type(static_cast<uchar>(buf[0]));
    // cout << type << endl;

    ifs.seekg(1446);
    ifs.read(buf,4);
    uint nFrame((static_cast<uchar>(buf[3]) << 24) | (static_cast<uchar>(buf[2]) << 16)
               | (static_cast<uchar>(buf[1]) << 8) | static_cast<uchar>(buf[0]));

    cout << xLen << ',' << yLen << ',' << type << ',' << nFrame << endl;

    if (nFrame == 1) {
        ofstream ofs(oName.c_str());

        uint nPx(xLen * yLen);
        vector<char> bv(nPx * sizeof(double));
        ifs.seekg(4100);
        ifs.read(&bv[0], bv.size());
        uint c(0);
        for (uint y(0); y<yLen; ++y) {
            for (uint x(0); x<xLen; ++x) {
                ofs << y << ' ' << x << ' ' << readIEEE754Double(&bv[c]) << endl;
                c += sizeof(double);
            }
            ofs << endl;
        }
    }
    else {
        cerr << "nFrames > 1 is not supported." << endl;
        return -1;
    }

    return 0;
}