I have string like this "0100110011001" I want to convert it to byte array such that the array contains zeros and ones the problem that after the conversion the array contains 49, 48 I don't why I tried many encoding for example I use the following code , and changed the encoding type
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte result = encoding.GetBytes(str);
any idea why that happen, and how to achieve the output I desire
You're asking for the text of the characters '0' and '1' to be encoded using UTF-8. In UTF-8, a '0' is represented by byte 48, and '1' is represented by byte 49. (Non-ASCII characters are represented by multiple bytes.)
It sounds like you really want a binary parser - you can use Convert.ToByte(text, 2) for a single byte, but I'm not sure there's anything in the framework to convert an arbitrary-length string to a byte array by parsing it as binary. I'm sure there are lots of third-party routines available on the net to do it though - it's not hard.
It's very important that you understand why your original code didn't work though - what Encoding.GetBytes is really for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With