Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a binary string representation to a byte array

Tags:

c#

binary

How do you convert a string such as "01110100011001010111001101110100" to a byte array then used File.WriteAllBytes such that the exact binary string is the binary of the file. In this case it would be the the text "test".

like image 208
ParoX Avatar asked Aug 08 '10 22:08

ParoX


People also ask

Can we convert string to byte array in Java?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.

What is string to byte array?

A String is stored as an array of Unicode characters in Java. To convert it to a byte array, we translate the sequence of characters into a sequence of bytes. For this translation, we use an instance of Charset. This class specifies a mapping between a sequence of chars and a sequence of bytes.

Is binary same as byte array?

Byte arrays mostly contain binary data such as an image. If the byte array that you are trying to convert to String contains binary data, then none of the text encodings (UTF_8 etc.) will work.


1 Answers

In case you don't have this LINQ fetish, so common lately, you can try the normal way

string input .... int numOfBytes = input.Length / 8; byte[] bytes = new byte[numOfBytes]; for(int i = 0; i < numOfBytes; ++i) {     bytes[i] = Convert.ToByte(input.Substring(8 * i, 8), 2); } File.WriteAllBytes(fileName, bytes); 

LINQ is great but there must be some limits.

like image 151
Maciej Hehl Avatar answered Sep 30 '22 00:09

Maciej Hehl