3

I am learning c# and I want to find out whether the 3rd bit in an integer is a 1 or 0.

So how I am approaching this is to convert the int to a binary. Then convert the string to an array. convert the array of string to an array of ints and slice on the 3rd bit and check value.

I cannot quite get this to happen. This is where I am at. I am using this example from SO to convert to array

using System;
using System.Text;

class Expression
{
    static void Main()
    {
        int number = 3;
        string binValue = Convert.ToString(number, 2);

        char[] array = binValue.ToCharArray();
        array<int> list = new List<int>();
        for (int i = 0; i < array.Length; i++)
        {
            list.add(value);
        }

        int[] binArr = list.ToArray();
        binArr[2] == 1? "Yes" : "No";
    }
}
1

2 Answers 2

3

That's entirely the wrong way to do it; just perform binary arithmetic:

bool bit3IsSet = (number & 4) != 0;

where the 4 is bit 3; you could also use:

int bitNumber = 3; // etc
bool bitIsSet = (number & (1 << (bitNumber-1))) != 0;

in the general-case.

Sign up to request clarification or add additional context in comments.

6 Comments

That's much easier. Oh well I learnt a lot going the wrong way anyway.
I am getting True for any number value. using System; using System.Text; class Expression { static void Main() { int number = 100; string binValue = Convert.ToString(number, 2); System.Console.WriteLine(binValue); bool bit3IsSet = (number & 4) != 0; System.Console.WriteLine(bit3IsSet); } } #Output C:\Users\Sayth\Documents\Scripts>Expression 1100100 True
@sayth and bit 3 is set for 100 ;p Try 96 or 104
I was counting the wrong way left to right not right too left.
@sayth ah, I see; traditionally, you usually count bit numbers right to left, i.e. starting with the LSB. You can do it the other way, but it will be harder; first you'd need to find the highest set bit, etc.
|
1

You do not need an array conversion: use String.Substring() Function (re: http://msdn.microsoft.com/en-us/library/system.string.substring%28v=vs.110%29.aspx ) to check the value of third bit (in your case: binValue.Substring(2,1); in a short form it could be written like the following:

bool _bit3 = (Convert.ToString(number, 2).Substring(2,1)=="1")? true:false;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.