ikegami ikegami - 1 year ago 110
C# Question

Convert byte array to string of bytes

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

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

string request_json = new JavaScriptSerializer().Serialize(dict);

This produces


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


(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

rbm rbm
Answer Source

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)_)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download