简体   繁体   中英

Reading data from .raw file

I have RAW file in grayscale with 8-bit data and I'm trying to read the data using simple program:

#include <fstream>
#include <iostream>
using namespace std;

int main(){
    char fileName[80] = "TEST.raw";
    //char buffer[255];
    ifstream fin(fileName);
    char ch;
    int i = 0;
    while (fin.get(ch)){
        cout << (unsigned int)ch << " ";
        i++;
    }
    cout << endl;
    cout << "i = " << i;
    fin.close();
    cin >> ch;
}

Some of values are higher than some specific value and I'm getting strange output. When i should get something like this:

(...) 34    34    34    36    43    59    88    123    151    166 (...)

i have:

(...) 34 34 34 36 43 59 88 123 4294967191 4294967206 (...)

I guess it's simple problem, but I have no idea how to do it correctly.

Change your ch variable declaration to

   unsigned char ch;
// ^^^^^^^^

and as recommended in the documentation change fin.get(ch) to

while (fin >> ch)

to fix this behavior.

char values need to be explicitly being signed or unsigned , when you use them as integer numerics. So if a value is bigger than 126 it's interpreted as a negative number. Negative numbers casted to unsigned int will set the high bits of those values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM