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 want 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]);
}
link|improve this question

feedback

1 Answer

up vote 4 down vote accepted

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 ushorts:

StringBuilder words;

for(int i = 0; i < words.Length; i++) {
    if (i > 0) words.Append(' ');
    words.AppendFormat({0:X4}", ushortArray[i]);
}
link|improve this answer
That's going from byte[] to string, and is good to know, but wanted to know how to deal with word array (ushort[]). – OIO Sep 5 '10 at 4:44
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.