Byte Array to Word Array to String
I have this byte[]: 00 28 00 60 00 30 10 70 00 22 FF FF
.
I want to combine each pair of bytes into a word: 0028 0060 0030 1070 0022 FFFF
.
I also wan开发者_如何学运维t to turn the word array into a string: "0028 0060 0030 1070 0022 FFFF"
(without using byte[]
).
I fixed SLaks code and it works:
StringBuilder sb = new StringBuilder();
for(var i = 0; i < words.Length; i++)
{
sb.AppendFormat("{0:X4} ", words[i]);
}
Like this:
StringBuilder words;
for(int i = 0; i < bytes.Length; i += 2) {
if (i > 0) words.Append(' ');
words.AppendFormat({0:X2}{1:X2}", bytes[i], bytes[i + 1]);
}
Edit: For ushort
s:
StringBuilder words;
for(int i = 0; i < words.Length; i++) {
if (i > 0) words.Append(' ');
words.AppendFormat({0:X4}", ushortArray[i]);
}
精彩评论