Re: bytes To Hex
- From: Arne Vajhøj <arne@xxxxxxxxxx>
- Date: Sun, 10 Feb 2008 22:01:28 -0500
Analizer1 wrote:
I Want The Fastest and Tightest Conversion Possible
Try and run the code below for some ideas.
Arne
==============================================
using System;
using System.Text;
namespace E
{
public class HexFun
{
private static char[] HEXDIGITS = "0123456789ABCDEF".ToCharArray();
public delegate string ToHex(byte[] b);
public static string ToHex1(byte[] b)
{
return BitConverter.ToString(b).Replace("-", "");
}
public static string ToHex2(byte[] b)
{
StringBuilder sb = new StringBuilder(2 * b.Length);
for(int i = 0; i < b.Length; i++)
{
sb.Append(b[i].ToString("X2"));
}
return sb.ToString();
}
public static string ToHex3(byte[] b)
{
StringBuilder sb = new StringBuilder(2 * b.Length);
for(int i = 0; i < b.Length; i++)
{
sb.Append(HEXDIGITS[b[i] / 16]);
sb.Append(HEXDIGITS[b[i] % 16]);
}
return sb.ToString();
}
public static string ToHex4(byte[] b)
{
StringBuilder sb = new StringBuilder(2 * b.Length);
for(int i = 0; i < b.Length; i++)
{
sb.Append(HEXDIGITS[b[i] >> 4]);
sb.Append(HEXDIGITS[b[i] & 0x0F]);
}
return sb.ToString();
}
public static string ToHex5(byte[] b)
{
char[] res = new char[2 * b.Length];
for(int i = 0; i < b.Length; i++)
{
res[2 * i] = HEXDIGITS[b[i] >> 4];
res[2 * i + 1] = HEXDIGITS[b[i] & 0x0F];
}
return new string(res);
}
private static char[] UH;
private static char[] LH;
static HexFun()
{
UH = new char[256];
LH = new char[256];
for(int i = 0; i < 256; i++)
{
UH[i] = HEXDIGITS[i / 16];
LH[i] = HEXDIGITS[i % 16];
}
}
public static string ToHex6(byte[] b)
{
char[] res = new char[2 * b.Length];
for(int i = 0; i < b.Length; i++)
{
res[2 * i] = UH[b[i]];
res[2 * i + 1] = LH[b[i]];
}
return new string(res);
}
public static void Test(byte[] b, int n, ToHex th)
{
DateTime dt1 = DateTime.Now;
for(int i = 0; i < n; i++)
{
th(b);
}
DateTime dt2 = DateTime.Now;
Console.WriteLine("{0:f4}", (dt2 - dt1).TotalSeconds);
}
private const int NBYT = 8;
private const int NREP = 4000000;
private static Random rng = new Random();
public static void Main(string[] args)
{
byte[] tst = { 1, 2, 3, 4, 255 };
Console.WriteLine(ToHex1(tst));
Console.WriteLine(ToHex2(tst));
Console.WriteLine(ToHex3(tst));
Console.WriteLine(ToHex4(tst));
Console.WriteLine(ToHex5(tst));
Console.WriteLine(ToHex6(tst));
byte[] b = new byte[NBYT];
rng.NextBytes(b);
Test(b, NREP, ToHex1);
Test(b, NREP, ToHex2);
Test(b, NREP, ToHex3);
Test(b, NREP, ToHex4);
Test(b, NREP, ToHex5);
Test(b, NREP, ToHex6);
Console.ReadKey();
}
}
}
.
- References:
- bytes To Hex
- From: Analizer1
- Re: bytes To Hex
- From: Peter Duniho
- Re: bytes To Hex
- From: Analizer1
- Re: bytes To Hex
- From: Jeroen Mostert
- Re: bytes To Hex
- From: Analizer1
- bytes To Hex
- Prev by Date: Re: configuration data for service?
- Next by Date: Newbie to dotnet
- Previous by thread: Re: bytes To Hex
- Next by thread: Re: bytes To Hex
- Index(es):