10

Suppose I have byte array.

byte[] a = new byte[] {0x33,0x43,0xFE};

I want to convert it to string.

 string str = convert(a);  

My str should look like this:

"33 43 FE"

How can I do that?

cheziHoyzer
  • 4,803
  • 12
  • 54
  • 81

2 Answers2

19

use bitconverter class

 BitConverter.ToString(Bytes);
Shafqat Masood
  • 2,532
  • 1
  • 17
  • 23
8

You could use this code:

byte[] a = new byte[] { 0x33, 0x43, 0xFE };
string str = string.Join(" ", a.Select(b => string.Format("{0:X2} ", b)));

so the convert method could be

string convert(byte [] a)
{
    return string.Join(" ", a.Select(b => string.Format("{0:X2} ", b)));
}

The X2 is used in order to get each byte represented with two uppercase hex digits, if you want one digit only for numbers smaller than 16 like 0xA for example, use {0:X} and if you want lowercase digits use {0:x} format.

Nikola Davidovic
  • 8,556
  • 1
  • 27
  • 33