2

I wrote a 16-byte binary key to Redis. When I query the key, it comes back in the following format:

\xc9;\xfd5\x80\x00\xa9Z\xc9\x0fb\xef\x7f\xd6V]

What format is this string? It looks like it ought to be hex (\x) but there are other characters in there that aren't valid hex characters.

How do I convert this string back into my original byte array byte[] (using C#)?

3
  • How are you querying for the key? The KEYS command? It seems very odd that you would get it back in a different format. It might be helpful to post the code that sets and queries the key Commented Jun 18, 2019 at 9:49
  • Is the initial array [c9, 3b, fd, 35, 80, 00, a9, 5a, c9, 0f, 62, ef, 7f, d6, 56, 5d] (in decimal: [201, 59, 253, 53, 128, 0, 169, 90, 201, 15, 98, 239, 127, 214, 86, 93])? Commented Jun 18, 2019 at 10:01
  • @ste-fu - yes, it was written with StackExchange.Redis as a byte[] and read back using the KEYS command hence why it came back in a different (printable) format. Commented Jun 19, 2019 at 16:36

1 Answer 1

2

It seems that you write a byte array byte[] but read it as a string. Some codes like 0x35 correspond to valid ASCII characters ('5'), some codes like 0x00 are not and thus represented as \x00 and so you have a strange looking string.

Let's try to parse the composed string back to original byte[].

First, let's get rid of \x.. format and have a valid string with a help of regular expressions:

  using System.Text.RegularExpressions;

  ...

  string source = @"\xc9;\xfd5\x80\x00\xa9Z\xc9\x0fb\xef\x7f\xd6V]";

  string result = Regex.Replace(
    source,
   @"\\x[0-9A-Fa-f]{2}",
    m => ((char)Convert.ToInt32(m.Value.Substring(2), 16)).ToString());

Second, let's get byte[] from the string, assuming that all characters are ASCII:

  byte[] array = result
    .Select(c => (byte)c)
    .ToArray();

Let's have a look at the array:

  Console.Write(string.Join(", ", array.Select(x => $"{x:x2}")));

Outcome:

  c9, 3b, fd, 35, 80, 00, a9, 5a, c9, 0f, 62, ef, 7f, d6, 56, 5d
Sign up to request clarification or add additional context in comments.

Comments

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.