Xaisoft
Xaisoft

Reputation: 46601

How could I get the bits from a string in 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?

Upvotes: 6

Views: 14571

Answers (3)

Scott Weinstein
Scott Weinstein

Reputation: 19117

You could do the following:

byte[] bytes = System.Text.UTF8Encoding.Default.GetBytes("Blue Box");
BitArray bits = new System.Collections.BitArray(bytes);

Upvotes: 15

John Rasch
John Rasch

Reputation: 63445

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"

Upvotes: 17

Jim H.
Jim H.

Reputation: 5579

That depends on what you mean by "bits". Are you talking about the ASCII representation? UTF8? UTF16? The System.Text.Encoding namespace should get you started.

Upvotes: 5

Related Questions