简体   繁体   中英

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

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. ie

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

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 0 s and 1 s (bytes):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM