Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I get the bits from a string in c#?

Tags:

c#

If I had the following string "Blue Box", how could I get the bits that make up the string in c# and what datatype would I store it in.

If I do just the letter "o", I get 111 as the bytes and 111 as the bits. Is it chopping off the 0's and if I do "oo", I get 111 for each o in the byte array, but for the bits, I get the value 28527. Why?

like image 486
Xaisoft Avatar asked Mar 17 '09 20:03

Xaisoft


2 Answers

If you want the bits in a string format, you could use this function:

public string GetBits(string input)
{
    StringBuilder sb = new StringBuilder();
    foreach (byte b in Encoding.Unicode.GetBytes(input))
    {
        sb.Append(Convert.ToString(b, 2));
    }
    return sb.ToString();
}

If you use your "Blue Box" example you get:

string bitString = GetBits("Blue Box");
// bitString == "100001001101100011101010110010101000000100001001101111011110000"
like image 148
John Rasch Avatar answered Oct 16 '22 03:10

John Rasch


You could do the following:

byte[] bytes = System.Text.UTF8Encoding.Default.GetBytes("Blue Box");
BitArray bits = new System.Collections.BitArray(bytes);
like image 32
Scott Weinstein Avatar answered Oct 16 '22 04:10

Scott Weinstein