Convert byte array to hex string

Byte array

A byte is 8 bits. A byte array is an array of bytes. You could use a byte array to store a collection of binary data, this data may be part of a data file, image file, compressed file, downloaded server response, or many other files. For large amounts of binary data, it would be better to use a streaming data type if your language supports it. With byte arrays, we have an ideal representation of this data. The byte array type allows you to store low-level representations. It is useful when optimizing certain methods.


byte array to string hexa

Hexadecimal string

Characters are represented as ASCII and they are 1 byte long, a byte could be represented with 2 digits in hexadecimal format for example 255 is 0xFF.

Convert a byte array to a hexadecimal string

byte[] bArray = { 1, 2, 4, 8, 16, 32 }; string strHex = BitConverter.ToString(bArray);
output
01-02-04-08-10-20

If you want it without the dashes, just remove them:

byte[] bArray = { 1, 2, 4, 8, 16, 32 }; string strHex = BitConverter.ToString(bArray).Replace("-", string.Empty);
output
010204081020

Convert a String Hex to byte array

using System; using System.Collections; using System.Linq; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { byte[] bArray = { 192, 168, 1, 1 }; string strHex = BitConverter.ToString(bArray).Replace("-", string.Empty); Console.WriteLine(strHex); Console.ReadKey(); byte[] bytes = new byte[strHex.Length / 2]; for (int i = 0; i < strHex.Length; i += 2) Console.WriteLine(bytes[i / 2] = Convert.ToByte(strHex.Substring(i, 2), 16)); Console.ReadKey(); } } }
output
C0A80101 192 168 1 1


NEXT.....Catch multiple exceptions at once: C#