CSharp · Console
using System;
public class Program
{
public static void Main()
{
// lets just make some booleans in an array for simplicity
bool[] boolsToSave = new bool[5];
bool[] boolsToLoad = new bool[5];
//they default to false we we just set 2 of them (3rd and 5th elements) to true so we can see it working
boolsToSave[2] = true;
boolsToSave[4] = true;
//an integer to hold the combined bools
int flags = 0;
// loop over each bool (order matters here)
for(int i = 0; i < boolsToSave.Length; i++)
{
//bit shift 1 << number of loop to plant into the int
if(boolsToSave[i])
{
// the | joins the two and the bitshifted 1 acts as a 2 to the power of i)
// in english the (1 << i) just lets i be identifier of the bit in the int
flags = flags | (1 << i);
}
}
//now your numbers are stored as an int! Go ahead and save this
Console.WriteLine(flags);
//lets looks at the int as binary to see This part is just to show what it is storing as
Console.WriteLine(Convert.ToString(flags, 2));
// result is 10100 which is exactly what we want! (read right to left it shows 0 for false and 1 for true for each boolean)
// then to convert back to bools
for(int i = 0; i < boolsToLoad.Length; i++)
{
boolsToLoad[i] = (flags & (1 << i)) > 0;
//writing to console just to display this is right
Console.WriteLine("Bool " + i + " is " + boolsToLoad[i].ToString());
}
}
}