sayth
sayth

Reputation: 7048

c# int to binary(string) to array

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";
    }
}

Upvotes: 3

Views: 1014

Answers (2)

Alexander Bell
Alexander Bell

Reputation: 7918

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;

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064114

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.

Upvotes: 3

Related Questions