Reputation: 2009
we have a text file containing binary values. say, we have a file "file.txt",it contains binary datat, say 11001010 the size of this file is 8 bytes. but we want these 8 bytes to be read as bits i.e. 8 bits and thus make 8 bits into 1 byte. How can we do it? we just know the procedure: 1. take a buffer and read individual value into buffer 2.if the buffer value reaches 8,make those 8 bits into a byte and write to a file.
thanks in advance.
Upvotes: 1
Views: 3231
Reputation: 2880
Just in case we are talking about bytes and not chars:
byte output;
using (var inFile = File.OpenRead("source"))
{
int offset = 0;
var data = new byte[8];
while (inFile.Read(data, offset, 8) == 8)
{
output = (byte)(data[0] << 7);
output += (byte)(data[1] << 6);
output += (byte)(data[2] << 5);
output += (byte)(data[3] << 4);
output += (byte)(data[4] << 3);
output += (byte)(data[5] << 2);
output += (byte)(data[6] << 1);
output += (byte)data[7];
offset += 8;
// write your output byte
}
}
Upvotes: 0
Reputation: 1503180
Given a string, I suspect you want Convert.ToByte(text, 2);
For more than a single byte, I don't think there's anything built in to convert a long string to a byte array like this, but you could use Substring
repeatedly if you want.
Upvotes: 3
Reputation: 66604
The following code reads such a text file as you describe. If the file contains a number of binary digits that is not divisible by 8, the extraneous digits are discarded.
using (var fileToReadFrom = File.OpenRead(@"..."))
using (var fileToWriteTo = File.OpenWrite(@"..."))
{
var s = "";
while (true)
{
var byteRead = fileToReadFrom.ReadByte();
if (byteRead == -1)
break;
if (byteRead != '0' && byteRead != '1')
{
// If you want to throw on unexpected characters...
throw new InvalidDataException(@"The file contains a character other than 0 or 1.");
// If you want to ignore all characters except binary digits...
continue;
}
s += (char) byteRead;
if (s.Length == 8)
{
fileToWriteTo.WriteByte(Convert.ToByte(s, 2));
s = "";
}
}
}
Upvotes: 1