problem with converting a char array of integers to an int

Hi

My problem:

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.

Thanks
Kenter
Char type supports numbers from 0 to 255 and I think that's the reason. Can't you just put this values directly to int array?
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?

Thanks
Kenter
what's the format of your image file. If it's a .bmp then the pixel should be stored in triplets (RGB). And each of those is between 0 and 255.
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 |= (unsigned char)s.get();
  }
  return ret;
}

// ... then to use, say you want to read an 'int' from the file:

int i = ReadInt<int>(myfile);
Thanks a lot for the answers. I will try these suggestions.

Cheers
Kenter
@Disch:
What is the difference whit this:
1
2
T i;
file.read( (char *)&i, sizeof(i) );


Last edited on
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.
@ne555:

My approach is endian-safe. Reading directly like your code is subject to system's endianness.

For example, say you have the following 4 bytes in a file: 01 23 45 67

With my approach, you will read 0x67452301 on any system.

WIth your approach you will get 0x67452301 on little endian systems only, and will get 0x1234567 on big endian systems.
Thanks
Topic archived. No new replies allowed.