Reputation: 749
I have a string that represents a byte
string s = "\x00af";
I write this string to a file so the file contains the literal "\x00af" and not the byte it represents, later I read this string from the file, how can I now treat this string as byte again (and not the literal)?
Here is a sample code:
public static void StringAndBytes()
{
string s = "\x00af";
byte[] b = Encoding.ASCII.GetBytes(s);
// Length would be 1
Console.WriteLine(b.Length);
// Write this to a file as literal
StreamWriter sw = new StreamWriter("c:\\temp\\MyTry.txt");
sw.WriteLine("\\x00af");
sw.Close();
// Read it from the file
StreamReader sr = new StreamReader("c:\\temp\\MyTry.txt");
s = sr.ReadLine();
sr.Close();
// Get the bytes and Length would be 6, as it treat the string as string
// and not the byte it represents
b = Encoding.ASCII.GetBytes(s);
Console.WriteLine(b.Length);
}
Any idea on how I convert the string from being a text to the string representing a byte? Thx!
Upvotes: 2
Views: 13349
Reputation: 6891
Is it a requirement for the file content to have the string literal? If no, then you might want to write the byte[] b
array directly to the file. That way when you read it, it is exactly, what you wrote.
byte[] b = Encoding.UTF32.GetBytes(s);
File.WriteAllBytes ("c:\\temp\\MyTry.txt", b);
b = File.ReadAllBytes ("c:\\temp\\MyTry.txt");
s = Encoding.UTF32.GetString (b);
If you need the file content to have the string literal, while being able to convert it to the original text written, you will have to choose the right encoding. I believe UTF32 to be the best.
b = new byte[4];
b[0] = Byte.Parse(s.Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier);
string v = Encoding.UTF32.GetString(b);
string w = "\x00af";
if (v != w)
MessageBox.Show("Diff [" + w + "] = [" + v + "] ");
else
MessageBox.Show("Same");
Upvotes: 1
Reputation: 29164
Not sure if I understand the question correctly, but you're not writing the string s
to the file. You have an extra \
in your WriteLine
statement! WriteLine("\\x00af")
writes the characters \
, x
, 0
, 0
, a
and f
, since the first \
acts as an escape to the second one ...
Did you mean
sw.WriteLine("\x00af");
or
sw.WriteLine(s);
instead? This works as expected in my tests.
Upvotes: 1