2

I have string which is storing only 1's and 0's .. now i need to convert it to a byte array. I tried ..

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                        byte[] d = encoding.GetBytes(str5[1]);

but its giving me byte array of ASCIIs like 48's and 49's but i want 1's and 0's in my byte array.. can any one help

3
  • If you had a string of length 8, are you looking for a single byte, or 8 bytes with the top 7 bits of each being clear? Commented Sep 21, 2012 at 13:37
  • Are you expecting "00110101" to give you a byte of 53? Commented Sep 21, 2012 at 13:43
  • @Matthew I don't think so: "i want 1's and 0's in my byte array" Commented Sep 21, 2012 at 13:46

3 Answers 3

5

That is the correct result from an encoding. An encoding produces bytes, not bits. If you want bits, then use bit-wise operators to inspect each byte. i.e.

foreach(var byte in d) {
    Console.WriteLine(byte & 1);
    Console.WriteLine(byte & 2);
    Console.WriteLine(byte & 4);
    Console.WriteLine(byte & 8);
    Console.WriteLine(byte & 16);
    Console.WriteLine(byte & 32);
    Console.WriteLine(byte & 64);
    Console.WriteLine(byte & 128);
}
Sign up to request clarification or add additional context in comments.

Comments

0
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                    byte[] d = encoding.GetBytes(str5[1]);
var dest[] = new byte();
var iCoun = 0;
var iPowe = 1;
foreach(var byte in d)
{
  dest[i++] = (byte & iPowe);
  iPowe *= 2;
}
foreach(var byte in dest)
{
  Console.WriteLine(byte);
}

1 Comment

based on marc's answer. In dest[] array you will find what you want!
0

There is no UTF encoding required, you say you have a string of '0's and '1's (characters) and you want to get to an array of 0s and 1s (bytes):

var str = "0101010";
var bytes = str.Select(a => (byte)(a == '1' ? 1 : 0)).ToArray();

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.