LoginSignup
0
0

More than 5 years have passed since last update.

c > readUInt32()の間違い

Last updated at Posted at 2015-08-22

以下の実装には間違いがあります。どこでしょう?

uint32_t readUInt32()
{
    char buf[10] = {0};
    int size = sizeof(uint32_t);
    m_fileStream->Read(buf, size);

    uint32_t res = 0;
    for(int idx=(size-1); idx>0; idx--) {
        res = res + buf[idx];
        res = res << 8;
    }
    res = res + buf[0];

    return res;
}

正解のコードはこちら

uint32_t TELFReader::readUInt32()
{
//  char buf[10] = {0};
    unsigned char buf[10] = {0};
    int size = sizeof(uint32_t);
    m_fileStream->Read(buf, size);

    uint32_t res = 0;
    for(int idx=(size-1); idx>0; idx--) {
        res = res + buf[idx];
        res = res << 8;
    }
    res = res + buf[0];

    return res;
}

char型で宣言した場合、コンパイル環境によってはsigned charになり、buf[.]の値がマイナスとなる時があり、読み取りに失敗する。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0