Converting from byte [] to string
I have the following 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 < length)
{
b[pos] = br.ReadByte();
pos++;
}
pos = 0;
while (pos < length)
{
Console.WriteLine(Convert.ToString(b[pos]));
pos++;
}
}
FILE_PATH is a const string that contains the path to the binary to read. A binary file is a mixture of integers and characters. The integers are 1 byte each and each character is written to the file as 2 bytes.
For example, a file has the following data:
YAELO, HOW YOU CHOOSE YOU, YOU ARE LOOKING FOR MORE // etc.
Note that each integer is associated with a string of characters following it. So 1 is associated with "HELLO LIKE YOU", and 45 with "YOU LOOKING FOR BIG", etc.
Now the binary is written (I don't know why, but I have to live with it), so "1" will only take 1 byte and "H" (and other characters) will take 2 bytes.
So, this is what the file actually contains:
0100480045 ... etc. Heres a breakdown:
01 - first byte for integer 1 0048 is 2 bytes for "H" (H - 48 in Hex) 0045 - 2 bytes for 'E' (E = 0x45)
etc .. I want my console to print a human readable format from this file: I want it to print "1 HELLO AS YOU ARE YOU" and then "45 YOU ARE LOOKING FOR GREAT" etc ...
Is this what I am doing right? Is there an easier / more efficient way? My line is Console.WriteLine (Convert.ToString (b [pos])); does only print out the integer value and not the actual character which I want. This is ok for integers in the file, but then how do I read characters?
Any help would be much appreciated. Thanks to
source to share
I think you are looking for Encoding.GetString .
Since your string data is 2 byte characters, how can you get your string:
for (int i = 0; i < b.Length; i++)
{
byte curByte = b[i];
// Assuming that the first byte of a 2-byte character sequence will be 0
if (curByte != 0)
{
// This is a 1 byte number
Console.WriteLine(Convert.ToString(curByte));
}
else
{
// This is a 2 byte character. Print it out.
Console.WriteLine(Encoding.Unicode.GetString(b, i, 2));
// We consumed the next character as well, no need to deal with it
// in the next round of the loop.
i++;
}
}
source to share
You can use String System.Text.UnicodeEncoding.GetString () which takes a byte [] array and creates a string. I found this link very helpful
source to share
using (BinaryReader br = new BinaryReader(File.Open(FILE_PATH, FileMode.Open, FileAccess.ReadWrite)))
{
int length = (int)br.BaseStream.Length;
byte[] buffer = new byte[length * 2];
int bufferPosition = 0;
while (pos < length)
{
byte b = br.ReadByte();
if(b < 10)
{
buffer[bufferPosition] = 0;
buffer[bufferPosition + 1] = b + 0x30;
pos++;
}
else
{
buffer[bufferPosition] = b;
buffer[bufferPosition + 1] = br.ReadByte();
pos += 2;
}
bufferPosition += 2;
}
Console.WriteLine(System.Text.Encoding.Unicode.GetString(buffer, 0, bufferPosition));
}
source to share