# Get 5 values from user in single veriable without array or any loop and find the max and min value

Your puzzle can be solved by bit shift manipulation to store and extract multiple variables within another. Below is a demonstration — see this blog post for an in depth explanation on what’s going on. If you are interested in additional bit-wise manipulation you can find more C++ examples here (easily convertible into C#).

enum Species
{
Camel,
Cat,
Caterpillar,
Cheetah,
Chimpanzee,
Cobra,
Cormorant,
Cougar,
Coyote,
Crab,
Crocodile,
}

void AddToBitfield(ref int bitfield, int bitCount, int value)
{
bitfield <<= bitCount;
bitfield |= value;
}

int ReadFromBitfield(ref int bitfield, int bitCount)
{
int value = bitfield & ((1 << bitCount) - 1);
bitfield >>= bitCount;
return value;
}

[Test]
public void BitwisePlayTest()
{
bool isAlive      = true;
bool isFiring     = false;
bool isMale       = true;
bool isFullHealth = false;
Species species = Species.Chimpanzee;

int bitfield = 0;

AddToBitfield(ref bitfield, 1, isAlive ? 1 : 0);
AddToBitfield(ref bitfield, 1, isFiring ? 1 : 0);
AddToBitfield(ref bitfield, 1, isMale ? 1 : 0);
AddToBitfield(ref bitfield, 1, isFullHealth ? 1 : 0);

isFullHealth = ReadFromBitfield(ref bitfield, 1) != 0;
isMale = ReadFromBitfield(ref bitfield, 1) != 0;
isFiring = ReadFromBitfield(ref bitfield, 1) != 0;
isAlive = ReadFromBitfield(ref bitfield, 1) != 0;

Assert.AreEqual(Species.Chimpanzee, species);
Assert.AreEqual(true, isAlive);
Assert.AreEqual(false, isFiring);
Assert.AreEqual(false, isFullHealth);
Assert.AreEqual(true, isMale);
}


Categories c# Tags