Reputation: 3
Is there a way to shorten this C# code?
byte[] temp = new byte[3];
InventoryKeyItemID = LoadData_readbytes(offset + 0x5ED, 3, file);
temp[0] = InventoryKeyItemID[0];
if (temp[0] >= 128)
{
checkedListBox_Inventory_KeyItems.SetItemChecked(7, true);
temp[0] -= 128;
}
if (temp[0] >= 64)
{
checkedListBox_Inventory_KeyItems.SetItemChecked(6, true);
temp[0] -= 64;
}
if (temp[0] >= 32)
{
checkedListBox_Inventory_KeyItems.SetItemChecked(5, true);
temp[0] -= 32;
}
if (temp[0] >= 16)
{
checkedListBox_Inventory_KeyItems.SetItemChecked(4, true);
temp[0] -= 16;
}
if (temp[0] >= 8)
{
checkedListBox_Inventory_KeyItems.SetItemChecked(3, true);
temp[0] -= 8;
}
if (temp[0] >= 4)
{
checkedListBox_Inventory_KeyItems.SetItemChecked(2, true);
temp[0] -= 4;
}
if (temp[0] >= 2)
{
checkedListBox_Inventory_KeyItems.SetItemChecked(1, true);
temp[0] -= 2;
}
if (temp[0] >= 1)
{
checkedListBox_Inventory_KeyItems.SetItemChecked(0, true);
}
What this code does,
Upvotes: 0
Views: 42
Reputation: 62512
You can use a for
loop with some bit shifting:
for(int i = 7; i >= 0; i--)
{
int number = 1 << i;
if(temp[0] >= number)
{
checkedListBox_Inventory_KeyItems.SetItemChecked(i, true);
temp[0] -= number;
}
}
Upvotes: 4