1

byte[] test = Form1.StrToByteArray("simpletext"); string encoded_text = BitConverter.ToString(test).Replace("-", "").ToLowerInvariant(); textBox1.Text = encoded_text;//73696d706c6574657874

as from this line "73696d706c6574657874" to get back "simpletext" ??

//StrToByteArray()

 public static byte[] StrToByteArray(string str)
 {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            return encoding.GetBytes(str);
 }
Alex
  • 15
  • 7

3 Answers3

4

Do you absolutely have to use hex to start with? One slightly more efficient (and reversible with framework methods) option would be to use base 64:

string base64 = Convert.ToBase64String(test);
byte[] originalBytes = Convert.FromBase64String(base64);
string text = Encoding.ASCII.GetString(originalBytes);

I personally wouldn't suggest using ASCII as your encoding, however - UTF-8 will work the same way for ASCII characters, but allow all of Unicode to be encoded.

If you do have to use hex, you'll need a method to parse hex - I have an example here.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • thx man, but i can use ASCII code, because http://stackoverflow.com/questions/2305676/problems-understanding-an-open-source-blowfish-api here i have string dec = "A-ґР^E—‹";//asdasdas - this text and must receive "asdasdas", but I get "3?}Fg5??", because i use ASCII – Alex Feb 22 '10 at 07:39
  • @Alex: Actually, that post shows "dec" containing *non-ASCII* characters... are you really happy to use a very lossy conversion? – Jon Skeet Feb 22 '10 at 07:41
  • thanks, I like your example is also useful. I have them both together :) – Alex Feb 22 '10 at 08:07
1
var input = "73696d706c6574657874";
var bytes = Enumerable
    .Range(0, input.Length)
    .Where(x => 0 == x % 2)
    .Select(x => Convert.ToByte(input.Substring(x, 2), 16))
    .ToArray();
Console.WriteLine(Encoding.ASCII.GetString(bytes));
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • That's a pretty inefficient parser, mind you. Have a look at the link in my answer for a more efficient version. I also have severe doubts about the rest of the strategy being used by the OP. – Jon Skeet Feb 22 '10 at 07:50
0

should have done so

public static byte[] StrToByteArray(string str)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            return encoding.GetBytes(str);
        }

//here im replace ASCIIEncoding to UTF8Encoding how said me Darin Dimitrov. respect man!!! very thx!!!!

and now i have result equal A-ґР^E—‹

Alex
  • 15
  • 7