2
byte[] val = { 3, 4, 5 };

Dictionary<String, Object> dict = new Dictionary<String, Object>();
dict.Add("val", val);
//...

string request_json = new JavaScriptSerializer().Serialize(dict);
Console.Out.WriteLine(request_json);

This produces

{"val":[3,4,5]}

What's the best way to convert val such that the above produces the following (or equivalent) instead:

{"val":"\u0003\u0004\u0005"}

(This is passed to a web service which expects a string of arbitrary bytes rather than an array of arbitrary bytes.)


In case it helps, I would have used the following in Perl:

pack "C*", @bytes

A more descriptive Perl solution would be:

join "", map { chr($_) } @bytes
8
  • This should do the trick: var b = String.Join("", val.Select(_ => @"\u"+_.ToString("X4"))); Commented Nov 8, 2016 at 22:00
  • var str = System.Text.Encoding.Default.GetString(byteArraVar); -> this will do the job, too bad the question is closed ;) Commented Nov 8, 2016 at 22:04
  • @Quantic, That's not the meaning it would have. Picture val containing the a .zip file, for example. Commented Nov 8, 2016 at 22:06
  • @mybirthname, That encodes according to the ANSI code page. That's no good. Commented Nov 8, 2016 at 22:12
  • But that does not print the \u which i thought was needed. Commented Nov 8, 2016 at 22:21

2 Answers 2

2

This should do the trick:

dict.Add("val", String.Join("", val.Select(_ => (char)_)));

or as suggested by Michael:

dict.Add("val", String.Concat(val.Select(_ => (char)_)));
Sign up to request clarification or add additional context in comments.

3 Comments

I think you can use String.Concat instead of String.Join with an empty delimiter.
What does _ mean in C# lamba?
@LeiYang it has no special meaning, it is just a valid variable name. the _ could just have been as easily called x or value
1

One possible solution:

StringBuilder sb = new StringBuilder(val.Length);
foreach (byte b in val) {
    sb.Append((char)b);
}

dict.Add("val", sb.ToString());

Note: Convert.ToChar(b) could be used instead of (char)b.

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.