0

is there any simple way to get a byte array of escaped string (Python repr() style) provided as TextBox input?

Example:

I want to convert string like this:

"ab\\x01c"

to array like this:

array[0] = 0x61;  
array[1] = 0x62;  
array[2] = 0x01;  
array[3] = 0x63;  
3
  • you won't get that array, unless you want the characters to be uppercased before conversion to bytes. Commented Mar 29, 2011 at 14:08
  • @Matt Ellen: I don't get your comment. 0x61 is 'a' so what is the problem? Commented Mar 29, 2011 at 15:59
  • ha! sorry, I miss read them as decimal, not hexadecimal Commented Mar 29, 2011 at 17:52

1 Answer 1

3

You can try the following:

using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
...
private string HexToStringMatchEvaluator(Match match)
{
    int intValue = int.Parse(match.Groups[1].Value, NumberStyles.AllowHexSpecifier);
    return Convert.ToChar(intValue).ToString();
}
...
string source = "ab\\x01c";
source = Regex.Replace(source, @"\\x(\d\d)", HexToStringMatchEvaluator);
byte[] bytes = Encoding.ASCII.GetBytes(source);

A brief explanation:

Regex.Replace looks for occurences of \x followed by two digits and passes each Match to our custom MatchEvaluator. The evaluator converts the specified value from hex to decimal and then to its equivalent Unicode character. The rest is obvious, I hope.

Hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

I think you got an extra \ before the x (you're using @")
@Aviad P., no, there must be 2 slashes in the regex: remember, we need to find a slash, followed by character 'x', followed by 2 digits. But in order to find a slash we must prefix literal '\' with another one, since the slash itself is an escape character in regexes. Without @ regex string would look like "\\\\x(\\d\\d)".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.