0

i have a list of integer in which i m storing RGB values of an image but after storing the sum of the values in integer then it become negative while all the values in array is positive nd this is the code!

        Bitmap bi = new Bitmap(@"E:\Store Signature Data\01\01_1.bmp");
        bi = ResizeImage(bi, 20, 20);

        Color[,] imgary = new Color[bi.Width, bi.Height];


        for (int x = 0; x < bi.Width; x++)
        {
            for (int y = 0; y < bi.Height; y++)
            {
                imgary[x, y] = bi.GetPixel(x, y);
            }
        }

        List<int> RGB = new List<int>();
        int c = 0;
        //RGB value= Red + (Green*256) + (Blue*256*256)
        for (int i = 0; i <20; i++)
        {
            for (int a = 0; a < 20; a++)
            {
                c++;
                Console.WriteLine(imgary[i,a]+"  "+c);
                Color Pixels = imgary[i, a];
                int Red = Pixels.R;
                int Blue = Pixels.B;
                int Green = Pixels.G;
                 RGB.Add(Red + (Green * 256) + (Blue * 256 * 256));

            }
        }


        int total = 0;
        for (int i = 0; i < RGB.Count; i++)
        {
            total += Math.Abs(RGB[i]);
        }
        Math.Abs(total);
        Console.WriteLine(total);

enter image description here

Shoaib Ahmed
  • 55
  • 1
  • 1
  • 8
  • 3
    Can you please show relevant code as a plain text? Maybe there is an integer overflow? Try to define your `total` which type has a wider range than `int`, like `long`, and see what happens. – Soner Gönül Jan 18 '16 at 09:29
  • 1
    Is the sum bigger than 2^32-1? That is the max int value and after exceeding that, the number wraps and becomes the min int value. If so, try using a long instead of an int. – Rico Herwig Jan 18 '16 at 09:31
  • 2
    integer max value is 2,147,483,647, you overflow it – Termininja Jan 18 '16 at 09:31
  • thanks u ! my problem resolved after changing from integer to long! – Shoaib Ahmed Jan 18 '16 at 09:37

2 Answers2

1

You insert 20 * 20 = 400 RGB values into your list. So let's say each of them would be blue. You would add 400 times 0xFF0000. The resulting sum would be 0x18FFFFE70, but an (32bit) int can take 0x7FFFFFFF as maximum value. The first bit (0x80000000) indicates the sign of the value.

Since your sum overflows the int (by using it's first bit), the resulting sum can be negative.

If you know there will be no more than the 400 values, consider using an Int64.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
0

Looks like your int is being assigned a value which is higher than the accepted maximum in C# (2,147,483,647), which causes it to overflow to a negative value.

Check these questions - they may be useful:

No overflow exception for int in C#?

Best way to handle Integer overflow in C#?

Community
  • 1
  • 1
Bassie
  • 9,529
  • 8
  • 68
  • 159