I'm working with the following code which adjusts an int based on multiple elements of an integer array. I am wondering if there's a cleaner, easier-to-read construct for this:
int Blue = 0;
int[] Adjustments = new int[24];
// ... populate Adjustments
if (Adjustments[0] == 255)
Blue = 128;
else if (Adjustments[0] == 0)
Blue = 0;
if (Adjustments[1] == 255)
Blue += 64;
else if (Adjustments[1] == 0)
Blue += 0;
if (Adjustments[2] == 255)
Blue += 32;
else if (Adjustments[2] == 0)
Blue += 0;
if (Adjustments[3] == 255)
Blue += 16;
else if (Adjustments[3] == 0)
Blue += 0;
if (Adjustments[4] == 255)
Blue += 8;
else if (Adjustments[4] == 0)
Blue += 0;
if (Adjustments[5] == 255)
Blue += 4;
else if (Adjustments[5] == 0)
Blue += 0;
if (Adjustments[6] == 255)
Blue += 2;
else if (Adjustments[6] == 0)
Blue += 0;
if (Adjustments[7] == 255)
Blue += 1;
else if (Adjustments[7] == 0)
Blue += 0;
Any suggestions?
Edit
Here is the revised version based on suggestions provided:
Blue = 0;
Green = 0;
Red = 0;
int[] Adjustments = new int[24];
// ... populate Adjustments
int[] AdjustmentStops = new[] { 128, 64, 32, 16, 8, 4, 2, 1 };
for (int i = 0; i < 8; i++)
{
Blue += Adjustments[i] == 255 ? AdjustmentStops[i] : 0;
Green += Adjustments[i + 8] == 255 ? AdjustmentStops[i] : 0;
Red += Adjustments[i + 12] == 255 ? AdjustmentStops[i] : 0;
}
1 << (7-i)
instead ofAdjustmentStops[i]
and get rid of the array, but it’s up to you to decide whether you find that too unreadable. \$\endgroup\$