1

I know there are many questions like these, but they don't seem to work as I expect, or probably I don't know how to use them.

Basically, how can I convert this:

65 78 61 6d 70 6c 65

Into this:

example

Basically like hex editors do (HxD, Microhex, and so on)

The reason for that is because I'd like to write data based on hexadecimal data, without using

using (BinaryWriter bw = new BinaryWriter(File.Open("file.txt", FileMode.Append)))
{
    bw.Write("foo bar"); // Here we are writing binary data normally, but not what I would want
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
winscripter
  • 109
  • 1
  • 11
  • What *is* this and where does it come from? Text files contain bytes too. When you use `File.ReadAllText` the bytes are converted to text using a specific codepage or encoding. You can pass the desired encoding to `File.Read...()` or `File.Write(..)` commands, StreamReader and StreamWriter – Panagiotis Kanavos Mar 14 '23 at 11:57
  • The one thing you *shouldn't* do is use `BinaryWriter`. – Panagiotis Kanavos Mar 14 '23 at 11:58
  • Does this answer your question? [How do you convert a byte array to a hexadecimal string, and vice versa?](https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa) – Scott Solmer Mar 14 '23 at 12:19
  • Your source, is that a byte-array, or a string with hexadecimal pairs separated by spaces? – Hans Kesting Mar 14 '23 at 12:20

2 Answers2

4

What you have there is text which has been turned into bytes using the ASCII (or possibly UTF-8) encoding.

So, you can use a suitable Encoding object to turn it back. For example:

byte[] bytes = new byte[] { 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65 };
string s = Encoding.ASCII.GetString(bytes);
Console.WriteLine(s);

Note that you're dealing with files or streams, there are many tools which use an Encoding internally to convert strings to bytes or vice versa:

  • File.ReadAllText / File.ReadAllLines / etc use an Encoding internally
  • StreamWriter / StreamReader let you read/write strings to/from a stream, and turn those into bytes using an Encoding
  • File.OpenText / File.CreateText / etc do the same thing with a file
canton7
  • 37,633
  • 3
  • 64
  • 77
2

Another solution is to cast byte to char:

 byte[] bytes = new byte[] { 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65 };
 string result = "";
 for(int i=0;i<bytes.Length;i++)
       result+=(char)bytes[i];

 Console.WriteLine(result); //example

You can also use the linq to convert byte array to char array. and Concate the characters using String.Join()

Console.WriteLine(string.Join("", bytes.Select(x => (char)x))); //example
Hossein Sabziani
  • 1
  • 2
  • 15
  • 20