There are even more variants of doing it, for example here.
The reverse conversion would go like this:
public static byte[] StringToByteArray(String hex) { int NumberChars = hex.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes; }
Edit: you can improve performance for long strings by using a single pass parser, like so:
public static byte[] StringToByteArray(String hex) { int NumberChars = hex.Length/2; byte[] bytes = new byte[NumberChars]; StringReader sr = new StringReader(hex); for (int i = 0; i < NumberChars; i++) bytes[i] = Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16); sr.Dispose(); return bytes; }
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Can you answer this question?
Write Answer1 Answers