Byte array to hexstring and vice versa

Byte array to hexstring and vice versa

The following two functions will convert the hexstring to byte array and viceversa 

 //Converts Hemadecimal string to byte array
 public static byte[] HexToByteArray(String HexString)     
   {            int NumberChars = HexString.Length;
                byte[] bytes = new byte[NumberChars / 2];    
                for (int i = 0; i < NumberChars; i += 2)   
          {           
       bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);     
          }  
    return bytes;
    }

//Converts byte array to hexadecimal string
 public static string BytesToHex(byte[] bytes)
  {
   StringBuilder hexString = new StringBuilder(bytes.Length);
   for (int i=0; i < bytes.Length; i++)
   {
    hexString.Append(bytes[i].ToString(”X2″));
   }
   return hexString.ToString();
  }

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.