Home
Manage Your Code
Snippet: Hex string to byte array and byte array to hex string (C#)
Title: Hex string to byte array and byte array to hex string Language: C#
Description: Converts hex string representation of a byte array to byte array and vice versa Views: 2344
Author: Szymon Kowalsky Date Added: 9/7/2007
Copy Code  
1		public static string byteArrayToString(byte[] array)
2		{
3			StringBuilder bob = new StringBuilder(array.Length);
4
5			foreach (byte singleByte in array)
6			{
7				bob.Append(singleByte.ToString("X2"));
8			}
9
10			return bob.ToString();
11		}
12
13		public static byte[] stringToByteArray(string text)
14		{
15			byte []bytes = new byte[text.Length / 2];
16
17			for(int i = 0 ; i < text.Length ; i += 2)
18			{
19				bytes[i / 2] = byte.Parse(text[i].ToString() + text[i + 1].ToString(), 
20					System.Globalization.NumberStyles.HexNumber);
21			}
22
23			return bytes;
24		}
25
26
Notes
Useful when working with System.Security.Cryptography namespace