[英]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);
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
的最佳方法是什么,以便上面的方法生成以下(或等效结果):
{"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.) (这被传递到Web服务,该服务需要一个任意字节的字符串,而不是任意字节的数组。)
In case it helps, I would have used the following in Perl: 如果有帮助,我会在Perl中使用以下内容:
pack "C*", @bytes
A more descriptive Perl solution would be: 一个更具描述性的Perl解决方案将是:
join "", map { chr($_) } @bytes
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)_)));
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
. 注意:可以使用Convert.ToChar(b)
代替(char)b
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.