Tuesday, November 25, 2014

Binary Number Lab



// OR (|) Turn all bits ON with an | of 1 for each bit you wish to turn on.
/// AND (&) Turn all bits OFF with an & of 0 for each bit you wish to turn off.
/// XOR (^) Toggles all bits ON or OFF depending on their current state.



namespace Binary_Lab
{
    public partial class Form1 : Form
    {
        string binaryNumber;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnConvertToInt_Click(object sender, EventArgs e)
        {
            // read the binary number and store it in a variable all the buttons can use.
            binaryNumber = txtBinary.Text;
            try
            {
                if (binaryNumber.Length > 32)
                {
                    throw new TooLongBinaryExcpetion("To many digits, use only 32 bits.\nNumber of bits used: " + binaryNumber.Length);
                }
                // convert that to an integer
                int binToInt = Convert.ToInt32(binaryNumber, 2);
                // display the integer
                txtInteger.Text = binToInt.ToString();
                txtBinary.Text = binaryNumber.PadLeft(32, '0');
            }
            catch (TooLongBinaryExcpetion tlb)
            {
                MessageBox.Show(tlb.Message);
            }
            catch (FormatException)
            {
                MessageBox.Show("Enter a binary number, EX: 10010101.");
            }
            catch (ArgumentOutOfRangeException)
            {
                MessageBox.Show("Enter at least one bit");
            }
            finally
            {
                txtBinary.Focus();
            }
        }

        private void btnBinSet_Click(object sender, EventArgs e)
        {
           
            /// OR (|) Turn all bits ON with an | of 1 for each bit you wish to turn on.
            /// use the binary input from above and set its first and last bits

            // read the binary number
            binaryNumber = txtBinary.Text;
            try
            {                          
                if (binaryNumber.Length > 32)
                {
                    throw new TooLongBinaryExcpetion("To many digits, use only 32 bits.\nNumber of bits used: " + binaryNumber.Length);
                }
                // Convert it to an integer
                int binToInt = Convert.ToInt32(binaryNumber, 2);

                // get the total number of digits
                int powerToRaise = binaryNumber.Length -1;

                // Get the mask by finding the position of the first bit and raising 2 to that position.
                // Add 1 to trigger the last bit.
                int maskEZWay = (int)Math.Pow(2, powerToRaise) + 1;
                int result = binToInt | maskEZWay;
                txtBinarySet.Text = Convert.ToString(result, 2).PadLeft(32, '0');
                txtBinary.Text = binaryNumber.PadLeft(32, '0');
            }
            catch (TooLongBinaryExcpetion tlb)
            {
                MessageBox.Show(tlb.Message);
            }
            catch (FormatException)
            {
                MessageBox.Show("Enter a binary number, EX: 10010101.");
            }
            catch (ArgumentOutOfRangeException)
            {
                MessageBox.Show("Enter at least one bit");
            }
        }

        private void btnBinClear_Click(object sender, EventArgs e)
        {
            /// AND (&) Turn all bits OFF with an & of 0 for each bit you wish to turn off.
            /// use the binary input above and clear its first 3 bits and last 3 bits

            // read the binary number
            binaryNumber = txtBinary.Text;
            try
            {
                if (binaryNumber.Length > 32)
                {
                    throw new TooLongBinaryExcpetion("To many digits, use only 32 bits.\nNumber of bits used: " + binaryNumber.Length);
                }

                // Convert it to an integer
                int binToInt = Convert.ToInt32(binaryNumber, 2);

                // get the total number of digits, subtract 6. This tells me how many positions exist that need to be ON (1)
                int bitsBetweenFirstAndLast3Bits = binaryNumber.Length - 6; // minus 6 positions for first and last 3


                // set the mask to be Math.Pow(2, 2+spaces)
                int mask = 0;
                for (int i = 0; i < bitsBetweenFirstAndLast3Bits; i++)
                {
                    mask += (int)Math.Pow(2, i + 3);
                }
                //int mask = (int)Math.Pow(2, bitsBetweenFirstAndLast3Bits)//(int)Math.Pow(2, bitsBetweenFirstAndLast3Bits) + (int)Math.Pow(2, bitsBetweenFirstAndLast3Bits - 1) + (int)Math.Pow(2, bitsBetweenFirstAndLast3Bits - 1) + 7; //7 comes from: 2^2 + 2^1 + 2^0

                // apply that mask
                int result = binToInt & mask;

                txtBinaryClear.Text = Convert.ToString(result, 2).PadLeft(32, '0');
                txtBinary.Text = binaryNumber.PadLeft(32, '0');
            }
            catch (TooLongBinaryExcpetion tlb)
            {
                MessageBox.Show(tlb.Message);
            }
            catch (FormatException)
            {
                MessageBox.Show("Enter a binary number, EX: 10010101.");
            }
            catch (ArgumentOutOfRangeException)
            {
                MessageBox.Show("Enter at least one bit");
            }
        }

        private void btnBinToggle_Click(object sender, EventArgs e)
        {
            /// XOR (^) Toggles all bits ON or OFF depending on their current state.
            /// use the binary input in txtBinary and toggle bits 8 thru 15

            //  00000000000000001000000100000000
            //  ^
            //  11111111111111110111111011111111
            //  ________________________________
            //  11111111111111110111111011111111
            // read the binary number
            binaryNumber = txtBinaryToggle.Text;
            try
            {
                if (binaryNumber.Length > 32)
                {
                    throw new TooLongBinaryExcpetion("To many digits, use only 32 bits.\nNumber of bits used: " + binaryNumber.Length);
                }

                // Convert it to an integer
                int binToInt = Convert.ToInt32(binaryNumber, 2);

                // If we wanted to toggle a single bit
                // say bit8, we simply XOR with the value of 256 (or 2^8)

                // for each bit position you wish to toggle, represented as zeroCounter
                // XOR with 2^zeroCounter
                int mask = 0;
                for (int i = 8; i < 16; i++)
                {
                   mask += (int)Math.Pow(2, i);
                }

                int result = binToInt ^ mask;
                // Display
                txtBinaryToggle.Text = Convert.ToString(result, 2).PadLeft(32, '0');

                // Pad the original number for easier visual comparison.
                //txtBinary.Text = binaryNumber.PadLeft(32, '0');
            }
            catch (TooLongBinaryExcpetion tlb)
            {
                MessageBox.Show(tlb.Message);
            }
            catch (FormatException)
            {
                MessageBox.Show("Enter a binary number, EX: 10010101.");
            }
            catch (ArgumentOutOfRangeException)
            {
                MessageBox.Show("Enter at least one bit");
            }
        }

        private void btnBinaryToggle1_Click(object sender, EventArgs e)
        {
            /// XOR (^) Toggles all bits ON or OFF depending on their current state.
            /// use the binary input in txtBinary and toggle bits 8 thru 15

            //  00000000000000001000000100000000
            //  ^
            //  11111111111111110111111011111111
            //  ________________________________
            //  11111111111111110111111011111111
            // read the binary number
            binaryNumber = txtBinary.Text;
            try
            {
                if (binaryNumber.Length > 32)
                {
                    throw new TooLongBinaryExcpetion("To many digits, use only 32 bits.\nNumber of bits used: " + binaryNumber.Length);
                }
                // Convert it to an integer
                int binToInt = Convert.ToInt32(binaryNumber, 2);



                // get the opposite of whatever we have in bits 8 thru 15.

                // Shift the bit from bit 0 to bit zeroCounter
                //for (int zeroCounter = 8; zeroCounter < 16; zeroCounter++)
                //{
                //    binToInt = binToInt ^ (1 << zeroCounter);
                //}

                for (int i = 8; i < 16; i++)
                {
                    binToInt = binToInt ^ (int)Math.Pow(2, i);
                }

                // Display
                txtBinaryToggle1.Text = Convert.ToString(binToInt, 2).PadLeft(32, '0');

                // Pad the original number for easier visual comparison.
                txtBinary.Text = binaryNumber.PadLeft(32, '0');
            }
            catch (TooLongBinaryExcpetion tlb)
            {
                MessageBox.Show(tlb.Message);
            }
            catch (FormatException)
            {
                MessageBox.Show("Enter a binary number, EX: 10010101.");
            }
            catch (ArgumentOutOfRangeException)
            {
                MessageBox.Show("Enter at least one bit");
            }
        }

        private void btnCountZeros_Click(object sender, EventArgs e)
        {
            // get user integer
            int userInt;
            if (int.TryParse(txtInt.Text, out userInt))
            {
                // count the zeros
                int zeros = CountBinaryZerosInGivenInteger(userInt);

                // display the number in binary and the count of zeros
                txtExpressedAsBinary.Text = Convert.ToString(userInt, 2);//.PadLeft(32, '0');
                txtZeroCount.Text = zeros.ToString();
            }
            else
            {
                MessageBox.Show("Enter a valid integer");
                txtInt.Focus();
            }
        }

        private int CountBinaryZerosInGivenInteger(int integerValue)
        {
            // convert the integer to a binary string
            string binaryString = Convert.ToString(integerValue, 2);
            int zeroCounter = 0;
            for (int i = 0; i < binaryString.Length; i++)
            {
                if (binaryString[i] == '0')
                {
                    zeroCounter++;
                }
            }
            return zeroCounter;          
        }
    }

    public class TooLongBinaryExcpetion : OverflowException
    {
        public TooLongBinaryExcpetion() : base("Binary number requires a maximum size of 32 bits.") { }
        public TooLongBinaryExcpetion(string message) : base(message) { }
        public TooLongBinaryExcpetion(string message, Exception innerException) : base(message, innerException) { }
    }
}
/// LAB:
/// Friday 11/21
/// ****************************
/// * NOTE: set = 1, clear = 0 *
/// ****************************
/// New Project
/// Provide the user with a textbox to enter a binary number (0's and 1's)
/// Convert that number to an int and display it in another text box. If the number of bits is more than 32
/// throw a "TooLongBinaryException"
/// 
/// use the binary input from above and set its first and last bits
/// use the binary input above and clear its first 3 bits and last 3 bits
/// use the binary input in txtBinary and toggle bits 8 thru 15
/// 
/// Write a method that takes an integer
/// and returns the number of 0's in the binary equivallent

No comments:

Post a Comment