tags:

views:

162

answers:

3
foreach (byte binaryOutupt in Encoding.ASCII.GetBytes(fileLine))
{
       fileOutput.Write(binaryOutupt.ToString("x2"));
 }

I got this code which let me convert string byte to hex but how do I reverse this?

+1  A: 

Don't know if this an elegant solution or not but seems to work(I've tested with a small string):

var sb = new StringBuilder("GET THE HEX LINE SOME WAY");
var strs = new string[sb.Length/2];

var i = 0;
var j = 0;
while(i<sb.Length)
{
    strs[j] = sb.ToString(i, 2);
    i += 2;
    j++;
}

foreach (var s in strs)
{
    Console.WriteLine("Hex: {0}, Orig ASCII:  {1}",
                         s, Int32.Parse(s,NumberStyles.HexNumber));
}

PS:- in first line initialize string builder with the hex line from file or some other source where you are writing it.

TheVillageIdiot
A: 

use io.streamreader on a filestream,memorystream, io stream then you can read the stream as a string

assuming your reading a bytestream

Jim
+1  A: 

Here is a sample for a complete round trip including your encoding.

// Input
String input = "Test1234";

// Encoding
String outputA = String.Empty;  
foreach (Byte b in Encoding.ASCII.GetBytes(input))
{
    outputA += b.ToString("X2");
}

// Decoding
Byte[] bytes = new Byte[outputA.Length / 2];
for (Int32 i = 0; i < outputA.Length / 2; i++)
{
    bytes[i] = Convert.ToByte(outputA.Substring(2 * i, 2), 16);
}
String outputB = Encoding.ASCII.GetString(bytes);

// Output
Console.WriteLine(input);
Console.WriteLine(outputA);
Console.WriteLine(outputB);

This is just a example to point into the right direction - obviously one should use StringBuilders and perform some error handling in production code if the input contains invalid characters or has a odd length.

Daniel Brückner