ValYouW
ValYouW

Reputation: 749

String representation of byte array

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

Answers (4)

Fun Mun Pieng
Fun Mun Pieng

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

MartinStettner
MartinStettner

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

Paul
Paul

Reputation: 564

Just parse a string representing each byte:

Byte b = Byte.Parse(s);

Upvotes: 0

PedroC88
PedroC88

Reputation: 3829

Use the Encoding.ASCII.GetString(byte[]) method. It is also available from all the others encoding. Make sure you always use the same encoding to decode the byte[] as you used to encode it or you won't get the same value every time.

Here's an example.

Upvotes: 0

Related Questions