Re: bytes To Hex



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 domain

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);

This works, but it's horribly inefficient. Of course, as long as you don't
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.


.



Relevant Pages

  • Re: bytes To Hex
    ... I needed to Convert Each Byte to a Hex String, ... below is a example...is the proper way, or is there a better way of accomplishing this ... This approach is over 50 times faster than yours. ... Avoid String.Formatand its relatives in tight loops. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: bytes To Hex
    ... I Want The Fastest and Tightest Conversion Possible ... For one thing, you will presumably want to *send* those hexstrings somewhere, and then you run smack-dab into I/O, which tends to bottleneck a lot more. ... Most C programmers would agree that my version is a paragon of readability. ... Extensive string manipulation *can* become a bottleneck fairly quickly, or even just a noticeable drag, and StringBuilder isn't a cure-all for string performance problems. ...
    (microsoft.public.dotnet.languages.csharp)