Print HEX values from a 8 bit byte?

  • Thread starter Thread starter David
  • Start date Start date
D

David

Is there an internal function in C# to translate a byte, or a byte
array, into a HEX string, Ex. "F1C1005E"? If it is int the doc, I am
missing it.
 
Here is one way:

byte b = 10;
string s = Convert.ToString(b, 16).PadLeft(2, '0');
Console.WriteLine("byte as Hex:"+s);
 
byte b = <some number>;
string hexValue = b.ToString("x");

You can also use the override of ToString with the NumberStyles enum.

-Rob Teixeira [MVP]
 
Is there an internal function in C# to translate a byte, or a byte
array, into a HEX string, Ex. "F1C1005E"? If it is int the doc, I am
missing it.


David,

The other replies are about single bytes, but if you are using Byte
arrays, then the BitConverter class may be what your after.

BitConverter.ToString(new Byte[2] {72, 72});

returns: "48-48"



Scott
 
byte[] bytes;
/.../
string hexed="";
foreach(byte b in bytes)
hexed+=b.ToString("x2");
 
Austin Ehlers said:
byte[] bytes;
/.../
string hexed="";
foreach(byte b in bytes)
hexed+=b.ToString("x2");

When you're going through a loop appending text and you don't know at
compile-time that the loop won't be repeated more than a few times, you
should always use a StringBuilder. In this case, you even know the
capacity the StringBuilder should use:

byte[] bytes;
/*...*/

StringBuilder sb = new StringBuilder(bytes.Length*2);
foreach (byte b in bytes)
{
sb.AppendFormat ("{0:x2}", b);
}
string result = sb.ToString();

For a 40K array, this makes the difference between taking over 6
seconds on my box, and under a 20th of a second.
 
Austin Ehlers said:
byte[] bytes;
/.../
string hexed="";
foreach(byte b in bytes)
hexed+=b.ToString("x2");

When you're going through a loop appending text and you don't know at
compile-time that the loop won't be repeated more than a few times, you
should always use a StringBuilder. In this case, you even know the
capacity the StringBuilder should use:

byte[] bytes;
/*...*/

StringBuilder sb = new StringBuilder(bytes.Length*2);
foreach (byte b in bytes)
{
sb.AppendFormat ("{0:x2}", b);
}
string result = sb.ToString();

For a 40K array, this makes the difference between taking over 6
seconds on my box, and under a 20th of a second.

Yeah, I thought about making it a StringBuilder, but I didn't want to
make the code more complicated. And you're right, the StringBuilder
version is much faster, even if you don't specify a default capacity
in the constructor.
 
Back
Top