Skip to content

Converting integers to bits/bytes

Dave

Asked Feb 25, 2008, 10:46 PM EST1 answer
Share
LinkedInX
Hello there. I am not a sessoned programmer and actually have very little experiance in c#. I have undertaken a project and one of the functions of my porject is to turn string numbers, into bits or bit vectors I beleive they are called. Like I said I am not a brilliant programmer and have had much help with this before. I have currently been changing the strings to ints first. But now I realised that bit vectors are more relevant. The code I am using is: private void button4_Click(object sender,System.EventArgs e) { string text =txtBoxBefore.Text; string expression =@"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"; text =Regex.Replace(text, expression, new MatchEvaluator(IpToUInt)); txtBoxAfter.Text=(text); } public static string IpToUInt (Match m) { string[] temp =m.Value.Split('.'); uint[] octets = new uint[4]; for (int i = 0; i < 4; i++) { octets[i] =uint.Parse(temp[i]); } return (octets[0] +(octets[1] << 8) + (octets[2] << 16) +(octets[3] << 24)).ToString(); } public static string IpFromUInt2 (uint ui) { uint[] octets = new uint[4]; octets[3] = ui >> 24; uint remainder = ui -(octets[3] << 24); octets[2] = remainder >> 16; remainder -= octets[2] << 16; octets[1] = remainder >> 8; remainder -= octets[1] << 8; octets[0] = remainder; string[] temp = new string[4]; for (int i = 0; i < 4; i++) { temp[i] = octets[i].ToString(); } return String.Join(".", temp); } Any help would be great. Thanks And im also guessing that seeing that ive tried to edit this three times now it doesnt allow for spaccing between sentances.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0

    Integers in C# are ALREADY represented in bits, more commonly called the binary representation.

    To access individual bits in an integer, i, you can use the AND operator (&) to zero out all bits except the one you're interested in.  You need a second integer to act as a mask, that has all zeros except a single one bit in the position you're interested in.

     

    C#
    For example, to access the first three (low-order) bits of i:
    
    int i = <some value>
    int mask = 1;   // 1 is the rightmost bit.
    int result;
    result = i & mask;     // Gives the first bit of i.
    mask <<= 1;     // Shift the single bit in mask to the second position.
    result = i & mask;     // Gives the second bit of i.

    mask <<= 1;     // Shift the mask bit to the third position.

    result = i & mask;

     

    In each case, result is zero if the corresponding bit is zero, and non-zero if the corresponding bit is 1.

    0