convert byte to binary
I have FLV file I stored it to byte array and I can read it byte by byte. I want to convert each byte to binary 0s and 1s
I want to convert variable b to binary 1s 0s. for example if b = 70 how to convert it to binary
what function I can use in C# to do this??
here is my code to read FLV file and store it byte array.
byte[] myArray = System.IO.File.ReadAllBytes(@"myFlvFile.flv");
i开发者_如何学Pythonnt r = 0;
foreach (var b in myArray)
{
r += 1;
txtBit.Text = Environment.NewLine + Convert.ToString(b);
if (r == 50)
return;
}
If you want a bit-string:
byte b = 100;
//Will be "1100100"
var bitstring = Convert.ToString(b, 2);
so in your example, just add , 2
The second argument is the base you want to use.
- 2 = binary (0 - 1)
- 8 = octal (0 - 7)
- 16 = hex (0 - F)
and secondary, I have a little improvement on your code :) this will do:
byte[] myArray = System.IO.File.ReadAllBytes(@"myFlvFile.flv");
for (r = 0; r < 50; r++)
{
txtBit.Text = Environment.NewLine + Convert.ToString(myArray[r], 2);
//Or if you want to append instead of replace? (I think you do, but that is not what your code do)
txtBit.Text += Environment.NewLine + Convert.ToString(myArray[r], 2);
}
there is still stuff to improve on - you may want to look at StringBuilder
or similar :-) (it is quite inefficient to concatenate the text the way you do it.)
The easiest way is to use BitArray class.
byte[] bytes = System.IO.File.ReadAllBytes(@"C:\yourfile.flv");
BitArray bits = new BitArray(bytes);
for (int counter = 0; counter < bits.Length; counter++)
{
Console.Write(bits[counter] ? "1" : "0");
if ((counter + 1) % 8 == 0)
Console.WriteLine();
}
and you will get something like this:
10000110
10110110
00001110
01011100
00000100
00001100
Obviously, using BitArray is quite ineffective for large files, so if you need to decode long files, use bit binary arithmetic.
Try something like this example program:
class Program
{
static void Main(string[] args)
{
const string filename = @"D:\Temp\dcs_0002.jpg";
var fileBytes = File.ReadAllBytes(filename);
var value = BytesAsBinaryString(fileBytes, 50);
Console.WriteLine(value);
}
public static string BytesAsBinaryString(IEnumerable<byte> bytes, int howMany)
{
var binaryStrings = from b in bytes
select Convert.ToString(b, 2);
return String.Join(Environment.NewLine, binaryStrings.Take(howMany));
}
}
You can use BitArray Class in .net
byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 };
BitArray myBA3 = new BitArray( myBytes );
for more information see below post
http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx
精彩评论