C#C
C#3y ago
9 replies
Yaell

uint value comparison for a 32 layer system (GameDev)

Hello. I'm looking for a way to see if these toggles are on or off by comparing the total value of the uint.

Description
How it works is that if the toggle is on, it returns the corresponding uint value and if it is off it returns zero. If we take top row for example, it goes from and index of 31 backwards to an index of 1. All these values that the toggles represents get added on top of each other and that results in the actual uint value. Taking the toggles on the top row as an example again, having them all toggled on it return uint.MaxValue and if they are all toggled off it returns 0.

Example
Lets take 5 toggles each respresenting 1, 2, 4, 8 and 16 respectively.

if all toggles are on it should give back the total number of all the numbers the toggle represents. If all toggles are off it should return zero. If the first toggle is on and the rest are off it should return 1. If the first and the third toggle (1 and 4) are active it should return a total number of 5.

What I Did
What I did now was to create a switch and check every possible number, but I dont think it is a smart way to do this. it was the only way I knew that would work;

//Derived from the example
void Foo(uint num)
{
  switch(num)
  {
    case 0:
    // No toggles active
    break;
    case 1:
    // First toggle is active
    break;
    case 3:
    // First and Second toggle are active
    break;
    case 7:
    // First, second and third toggles are active
    break;
    case 15:
    // 1st, 2nd, 3rd, 4th toggles are active
    break;
    case 31:
    // 1st, 2nd, 3rd, 4th, 5th toggles are active
    break;
    //etc.
  }
}


What I am hoping for
I was looking for a better/more elegant way to approach this problem. If anyone can point me in a direction, I'll be grateful. Thanks for reading.
Schermafbeelding_2023-09-20_135909.png
Was this page helpful?