Note that there are some explanatory texts on larger screens.

plurals
  1. POConverting from byte[] to string
    text
    copied!<p>I have the following code:</p> <pre><code>using (BinaryReader br = new BinaryReader( File.Open(FILE_PATH, FileMode.Open, FileAccess.ReadWrite))) { int pos = 0; int length = (int) br.BaseStream.Length; while (pos &lt; length) { b[pos] = br.ReadByte(); pos++; } pos = 0; while (pos &lt; length) { Console.WriteLine(Convert.ToString(b[pos])); pos++; } } </code></pre> <p>The FILE_PATH is a const string that contains the path to the binary file being read. The binary file is a mixture of integers and characters. The integers are 1 bytes each and each character is written to the file as 2 bytes.</p> <p>For example, the file has the following data :</p> <p>1HELLO HOW ARE YOU45YOU ARE LOOKING GREAT //and so on</p> <p>Please note: Each integer is associated with the string of characters following it. So 1 is associated with "HELLO HOW ARE YOU" and 45 with "YOU ARE LOOKING GREAT" and so on.</p> <p>Now the binary is written (I do not know why but I have to live with this) such that '1' will take only 1 byte while 'H' (and other characters) take 2 bytes each.</p> <p>So here is what the file actually contains:</p> <p>0100480045..and so on Heres the breakdown:</p> <p>01 is the first byte for the integer 1 0048 are the 2 bytes for 'H' (H is 48 in Hex) 0045 are the 2 bytes for 'E' (E = 0x45)</p> <p>and so on.. I want my Console to print human readable format out of this file: That I want it to print "1 HELLO HOW ARE YOU" and then "45 YOU ARE LOOKING GREAT" and so on...</p> <p>Is what I am doing correct? Is there an easier/efficient way? My line Console.WriteLine(Convert.ToString(b[pos])); does nothing but prints the integer value and not the actual character I want. It is OK for integers in the file but then how do I read out characters?</p> <p>Any help would be much appreciated. Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload