Drone
Drone

Reputation: 181

C# can't convert string to byte array to desired result?

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

Upvotes: 2

Views: 525

Answers (3)

weston
weston

Reputation: 54781

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();

Upvotes: 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);
}

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062780

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);
}

Upvotes: 5

Related Questions