1

I use this method which I saw in one of the questions to convert ascii to binary string:

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

But, If the input is something like the message bellow which contains chars like 'space' or others:

"Hello, How are you?"

The above method is building a sequence of 6 or 7 bit. When I try to decode the long sequence(which I know every 8 bit is a character) I get a big problem that part of the message chars are 6 or 7 or 8 bit and everything is mixed up. How can I improve it? Thanks

0

2 Answers 2

2

how about

public string GetBits(string input)
{
    return string.Concat(input.Select(x => Convert.ToString(x, 2).PadLeft(8, '0')));
}
Sign up to request clarification or add additional context in comments.

3 Comments

Won't this return 000000x0 for input 0?
@CodeCaster - a "0"-String leads to "00110000"
I don't mean a "0" string, but a string consisting of a single 0 char. Edit: nevermind, I looked at the wrong docs and though this printed 0x(bits), but the 0x part didn't come from Convert.ToString().
1

You problem is leading zeros. If you want to return 8 bits for every character, then you have to add leading zeros. I used PadLeft in your case.

public string GetBits(string input)
{
    StringBuilder sb = new StringBuilder();
    foreach (byte b in ASCIIEncoding.UTF8.GetBytes(input))
    {
        sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
    }
    return sb.ToString();
}

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.