Bitmask without and's and or's
Well, ran into an issue with a programming language that didn't support and's and or's. Turns out we really didn't need to do it, but I wanted to figure how to do it. So, I did. Here's the c# code to do it. It's pretty straight forward.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BitChecker
{
class Program
{
static void Main(string[] args)
{
int number = 0;
int bitToFind = 0;
int maxBit = 0;
int newNumber = 0;
Console.WriteLine("Number: ");
while (!int.TryParse(Console.ReadLine(), out number) || number < 0)
{
Console.WriteLine("Try again. Put in a number. 0-255");
}
Console.WriteLine("Bit Number to find, 1 is farthest left.");
while (!int.TryParse(Console.ReadLine(), out bitToFind) || bitToFind < 1)
{
Console.WriteLine("Try again. Put in a number. 1-16, 1 is farthest left");
}
bitToFind--; //since binary is 0 based.
newNumber = number;
for (int i = 0; Math.Pow(2, i) <= number; i++)
{
maxBit = i;
}
if (maxBit < bitToFind)
{
maxBit = bitToFind;
}
string bitMask = string.Empty;
bool isSet = false;
for (int i = maxBit; i >= 0; i--)
{
if (newNumber >= Math.Pow(2, i))
{
bitMask = "1" + bitMask;
if (i == bitToFind) { isSet = true; }
newNumber = newNumber - (int)Math.Pow(2, i);
}
else
{
bitMask = "0" + bitMask;
}
}
Console.WriteLine("IS SET: {0}", isSet);
Console.WriteLine("BITMASK:{0}", bitMask);
Console.ReadLine();
}
}
}