'lo
Right now I'm using System.Web.Configuration.MachineKey.ByteArrayToHexString() to convert Byte arrays to Hex strings.
As you can tell, it is rather ghastly and requires a reference to System.Web in the containing project. Far from ideal.
I've had a look at the method (courtesy of Lutz Roeder's Reflector) but it makes use of "Fixed" blocks, which the VB syntax doesn't support.
So does anyone know of a good algorithm to perform the conversion?
-
-
You would want to profile for speed impact, but you can do it a byte at a time with System.Convert.ToString( byte , int toBase );
So using a StringBuilder and this method you could create your own function to do it, and probably quite efficiently, though I don't know compared to your current method.
Jared
-
You can also just step through using something like:
StringBuilder sb = new StringBuilder();
foreach( byte b in myByteArray )
{
sb.Append( b.ToString( "x" ) );
}
string myHex = sb.ToString();
The overloaded ToString() method for a byte allows you to put in in the format you want.
Jared -
One tiny prob with that: you actually need to specify "x2" as the format string to make sure a leading zero is added when the byte is less than 0xF.
StringBuilder hex = new StringBuilder();
foreach (byte b in new byte[] { 0x01, 0xa, 0xa })
hex.AppendFormat("{0:x2}", b);
Console.WriteLine(hex.ToString()); -
MSDN example: ToHexString
-
W3bbo wrote:'lo
Right now I'm using System.Web.Configuration.MachineKey.ByteArrayToHexString() to convert Byte arrays to Hex strings.
As you can tell, it is rather ghastly and requires a reference to System.Web in the containing project. Far from ideal.
I've had a look at the method (courtesy of Lutz Roeder's Reflector) but it makes use of "Fixed" blocks, which the VB syntax doesn't support.
So does anyone know of a good algorithm to perform the conversion?
Edit: Won't work. Haven't taken into account 10=A
I think this'll do it. Untested.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < byteArray.Length; i++)
{
byte b = byteArray[i];
byte d1 = (b && 240) >> 4;
byte d2 = (b && 15);
sb.Append(new char(48 + d1));
sb.Append(new char(48 + d2));
}
return sb.ToString();
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.