- Posted by azazeal on November 20, 2008
- Kick it! |
I'll post a couple of method extensions I often use in my projects:
The first one is a function that, given a byte array, converts it to a string hex representation and the second transforms a hex representation string to it's original byte array.
public static string ToHexString( this byte[] bytes )
{
if ( bytes == null ) return ( string )null;
string ret = string.Empty;
foreach ( byte b in bytes )
ret += b.ToString( "x2" );
return ret;
}
public static byte[] ToHexArray( this string str )
{
if ( string.IsNullOrEmpty( str ) )
return new byte[] { };
if ( str.Length % 2 != 0 )
return new byte[] { };
int byteLength = str.Length / 2;
byte[] ret = new byte[byteLength];
int j = 0;
for ( int i = 0; i < str.Length; i += 2 )
{
string hex = str.Substring( i, 2 );
ret[j] = byte.Parse( hex, System.Globalization.NumberStyles.HexNumber );
j++;
}
return ret;
}
Now that I think of it I'll post also a third method extension that determines whether a string is indeed a hex representation.
public static bool IsValidHexString( this string str )
{
if ( string.IsNullOrEmpty( str ) ) return false;
if ( string.Length % 2 != 0)
return false;
string map = "0123456789abcdef";
foreach ( char c in str.ToLower( ) )
if ( !map.Contains( c ) )
return false;
return true;
}
I really hope these 3 extensions will be of use to you one day :)
Till the next post, keep coding.