patterncsharpMinor
Adjusting integer based on multiple elements in int array
Viewed 0 times
elementsarrayadjustingmultiplebasedintinteger
Problem
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:
Any suggestions?
Edit
Here is the revised version based on suggestions provided:
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;
}Solution
At the risk of being 'clever':
Since in effect you're setting bits anyway I think using bitwise operations is idiomatic here.
int Blue = 0;
int[] Adjustments = new int[24];
// ... populate Adjustments
for (int blueIndex=0; blueIndex<8; blueIndex++)
{
if (Adjustments[blueIndex] == 255)
{
Blue |= (1 << (7 - blueIndex));
}
}Since in effect you're setting bits anyway I think using bitwise operations is idiomatic here.
Code Snippets
int Blue = 0;
int[] Adjustments = new int[24];
// ... populate Adjustments
for (int blueIndex=0; blueIndex<8; blueIndex++)
{
if (Adjustments[blueIndex] == 255)
{
Blue |= (1 << (7 - blueIndex));
}
}Context
StackExchange Code Review Q#1557, answer score: 7
Revisions (0)
No revisions yet.