Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert byte to binary

Tags:

c#

flv

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");

int r = 0;
foreach (var b in myArray)
{
  r += 1;
  txtBit.Text = Environment.NewLine + Convert.ToString(b);

  if (r == 50)
    return;
}
like image 929
Eyla Avatar asked Jun 26 '26 20:06

Eyla


2 Answers

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.)

like image 141
Lasse Espeholt Avatar answered Jun 29 '26 12:06

Lasse Espeholt


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.

like image 35
Dmitry Karpezo Avatar answered Jun 29 '26 11:06

Dmitry Karpezo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!