public static byte[] HexToBytes(string hexInput) { if (string.IsNullOrEmpty(hexInput)) { return(null); } string buffer; if (hexInput.Length % 2 != 0) { buffer = "0" + hexInput.ToUpperInvariant(); } else { buffer = hexInput.ToUpperInvariant(); } List <byte> bytes = new List <byte>(); for (int i = 0; i < buffer.Length; i += 2) { if (!(CharUtils.IsLegalHex(buffer[i]) && CharUtils.IsLegalHex(buffer[i + 1]))) { return(null); } bytes.Add(HexToByte(buffer.Substring(i, 2))); } return(bytes.ToArray()); }
public static byte[] BinaryToBytes(string binaryInput) { if (string.IsNullOrEmpty(binaryInput)) { return(null); } string buffer; if (binaryInput.Length % 8 != 0) { StringBuilder sb = new StringBuilder(); int left = 8 - (binaryInput.Length % 8); for (int i = 0; i < left; i++) { sb.Append('0'); } sb.Append(binaryInput); buffer = sb.ToString(); } else { buffer = binaryInput; } List <byte> bytes = new List <byte>(); for (int i = 0; i < buffer.Length; i += 8) { if (!(CharUtils.IsLegalHex(buffer[i]) && CharUtils.IsLegalHex(buffer[i + 1]) && CharUtils.IsLegalHex(buffer[i + 2]) && CharUtils.IsLegalHex(buffer[i + 3]) && CharUtils.IsLegalHex(buffer[i + 4]) && CharUtils.IsLegalHex(buffer[i + 5]) && CharUtils.IsLegalHex(buffer[i + 6]) && CharUtils.IsLegalHex(buffer[i + 7]))) { return(null); } bytes.Add(BinaryToByte(buffer.Substring(i, 8))); } return(bytes.ToArray()); }