Как произвольный байт на входе преобразовать в биты - C#
Формулировка задачи:
Собственно, вопрос в заголовке )) Подскажите, пожалуйста! ))
Решение задачи: «Как произвольный байт на входе преобразовать в биты»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Collections;
using System.IO;
namespace ParseByte
{
static class BitStream
{
static char[] bitbuffer = new char[4096]; //буфер
static int cntWrite = 0; //счетчик на запись
//Парсит байт в биты и записывает в буфер. Принимает байт и файловый поток
static public void ByteToBit(byte[]masByte, BinaryWriter fs)
{
BitArray oneByte = new BitArray(masByte);
foreach (bool bit in oneByte)
{
if (bit && cntWrite < 4096) //если true
{
bitbuffer[cntWrite] = '1';
cntWrite++;
}
else if (!bit && cntWrite < 4096) //если false
{
bitbuffer[cntWrite] = '0';
cntWrite++;
}
else
{
fs.Write(bitbuffer, 0, bitbuffer.Length);
cntWrite = 0;
break;
}
}
}
//Биты из файла в 512 байт
static public void BitsTo512Byte(BinaryReader bread, FileStream fend)
{
char oneByte;
int j = 0, check = 0, i;
BitArray realBitBuffer = new BitArray(4096);
BitArray tmp = new BitArray(8);
byte[] bytes = new byte[512];
for (i = 1; i < 4097; i++)
{
if ((check = bread.PeekChar()) != -1)
{
oneByte = bread.ReadChar();
if (oneByte == '1')
realBitBuffer[i - 1] = true;
else if (oneByte == '0')
realBitBuffer[i - 1] = false;
else
Console.WriteLine("В байте неверное значение!");
}
}
for (int k = 0; k < Math.Ceiling(realBitBuffer.Count/8.0); k++) //Делаем столько проходов, сколько раз у нас встречаются комбинации по 8 бит! Ceiling округляет до верхнего целого
for (i = 0; i < 8 && j < realBitBuffer.Count; i++, j++)
{
tmp[i] = realBitBuffer[j];
if (i == 7 || j == realBitBuffer.Count) // Пора сбрасывать биты в байт!
tmp.CopyTo(bytes, k); //парсим биты в байты, к - текущий индекс массива байтов bytes
}
BurnBytes(bytes, fend);
}
//Считываем весь файл с помощью BitsTo512Byte
static public void ReadAllBits(BinaryReader bread, FileStream fend)
{
int i;
while ((i = bread.PeekChar()) != -1)
BitsTo512Byte(bread, fend);
}
//Записывает массив байтов на входе в файл
static public void BurnBytes(byte[] bytes, FileStream fend)
{
foreach (byte b in bytes)
fend.WriteByte(b);
}
//Все байты преобразовывает в биты через ByteToBit
static public void AllBytesToBits(FileStream fs, BinaryWriter wout) //(откуда считывать, куда писать биты)
{
int bt;
byte[] masByte = new byte[1];
do
{
bt = fs.ReadByte();
if (bt != -1)
{
masByte[0] = (byte)bt;
ByteToBit(masByte, wout);
}
} while (bt != -1);
}
}
class MainProgram
{
static void Main(string[] args)
{
string strChoise;
int choise = 0;
Console.WriteLine("Что вы желаете сделать: \n 1. Преобразовать файл в биты\n 2. Преобразовать биты в файл");
Console.Write("Ваш выбор: ");
strChoise = Console.ReadLine();
choise = Int32.Parse(strChoise);
switch (choise)
{
case 1:
try
{
Console.Write("Введите название файла, откуда считывать биты: ");
string strIn = Console.ReadLine();
FileStream fin = new FileStream(strIn, FileMode.Open);
Console.Write("Введите название файла, куда сохранять считанные биты: ");
string strOut = Console.ReadLine();
BinaryWriter fswrite = new BinaryWriter(new FileStream(strOut, FileMode.Create, FileAccess.Write));
BitStream.AllBytesToBits(fin, fswrite); //тут идет основная работа :)
}
catch (IOException exc)
{
Console.WriteLine("Ошибка работы с файлом:\n" + exc.Message);
Console.ReadKey();
}
break;
case 2:
try
{
Console.Write("Введите название файла, откуда считывать биты: ");
string strIn = Console.ReadLine();
BinaryReader bread = new BinaryReader(new FileStream(strIn, FileMode.Open, FileAccess.Read));
Console.Write("Введите название и путь конечного файла: ");
string strOut = Console.ReadLine();
FileStream fend = new FileStream(strOut, FileMode.Create);
BitStream.ReadAllBits(bread, fend);
}
catch (IOException exc)
{
Console.WriteLine("Ошибка работы с файлом:\n" + exc.Message);
Console.ReadKey();
}
break;
}
}
}
}