I am reading some binary image and keep their pixel values in a char array. Then convert them to integer to use for my purposes. This is working for low pixel values. But I am having some problems with high pixel values!.
For example, if the original pixel value is 3375, my result is 61.
another example: org. pix. value: 3452, result:-127.
I have a int array and char array that contains original image values. For casting, I am doing this way:
within a loop
intArr[i][j] = (int)orgImgCharArray[i][j]
It is working values like 100, 50, 150 but not for higher values.
Yeah your right. I am using ifstream::read member function to read the binary data. And it takes char array as parameter. Do you have a suggestion to do this in a different way?
It is not a known format. It is a format which used in my university. And it is for monochromic images. So no rgb vales. And the values for some images ranges from 0-255 and for some the range is higher.
And what about wide characters? Do you try to do it using them? In wide characters each character stores symbol on 2 bytes, so you can write a numbers from 0 to 65535.
1 'char' is 1 byte. If you want to read a variable that's larger than 1 byte, you have a few options.
The endian-safe way is to read the variable one byte at a time and use bitshifting to construct the larger value.
Here's an imperfect, but functional function you can use:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template <typename T>
T ReadInt(istream& s)
{
T ret = 0;
for(int i = 0; i < sizeof(T); ++i)
{
ret <<= 8;
ret |= (unsignedchar)s.get();
}
return ret;
}
// ... then to use, say you want to read an 'int' from the file:
int i = ReadInt<int>(myfile);
It allows you to read binary data from a file. read() (write() function too) expects pointer to a char, so adress of the object 'i' has to be thrown on a pointer to a char. Second argument of read() function is size of object you want to store. It's basically a quantity of chars to save.