Re: bytes To Hex
- From: "Analizer1" <dvs_bis@xxxxxxxxxxxxx>
- Date: Tue, 5 Feb 2008 13:19:39 -0800
this was my 1st Run at this type of conversion...
so your remarks are welcome...
I Want The Fastest and Tightest Conversion Possible
Tks
"Jeroen Mostert" <jmostert@xxxxxxxxx> wrote in message
news:47a8cd3a$0$85781$e4fe514c@xxxxxxxxxxxxxxxxx
Analizer1 wrote:
My Byte[] array consists of DirectoryServices Users Sid from the domainThis works, but it's horribly inefficient. Of course, as long as you don't
I needed to Convert Each Byte to a Hex String , Then Concatenate each
following byte
below is a example...is the proper way, or is there a better way of
accomplishing this
uint uDec;
for (int x = 0; x < aBytes.GetLength(0); x++)
{
uDec = Convert.ToUInt32(aBytes[x]);
sHexId.Append(String.Format("{0:x2}",uDec));
}
Console.WriteLine(sHexId);
need to do it a few hundred times every second, it doesn't matter. And
even if you do, this function probably won't be the bottleneck. Still, if
you do need this to be fast...
const string hexDigits = "0123456789abcdef";
int bl = aBytes.Length;
char[] result = new char[bl * 2];
for (int n = 0; n != bl; ++n) {
result[n * 2 + 0] = hexDigits[aBytes[n] / 16];
result[n * 2 + 1] = hexDigits[aBytes[n] % 16];
}
Console.WriteLine(new string(result));
This approach is over 50 times faster than yours. If you don't like to
spend that much keystrokes on it, even this oneliner is better (better
still than doing it yourself with a StringBuilder):
Console.WriteLine(BitConverter.ToString(aBytes).Replace("-","");
Avoid String.Format() and its relatives in tight loops. If you need to do
positional replacement or locale-dependent formatting they're well worth
it (it's much more readable than gluing strings together yourself) but for
trivial conversions like these, repeated in a loop, they're not good.
--
J.
.
- Follow-Ups:
- Re: bytes To Hex
- From: Arne Vajhøj
- Re: bytes To Hex
- From: Jon Skeet [C# MVP]
- Re: bytes To Hex
- 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
- bytes To Hex
- Prev by Date: Re: Get/Set vs Public Variables
- Next by Date: Re: Creating COM object written in C#
- Previous by thread: Re: bytes To Hex
- Next by thread: Re: bytes To Hex
- Index(es):
Relevant Pages
|