Created
March 15, 2016 18:42
-
-
Save morbidcamel101/735ff671a6b9e5f67fa9 to your computer and use it in GitHub Desktop.
Converting Hex Strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static byte[] HexStringToByteArray(string input) { | |
byte[] Bytes; | |
int ByteLength; | |
string HexValue = "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9|||||||\xA\xB\xC\xD\xE\xF"; | |
ByteLength = input.Length / 2; | |
Bytes = new byte[ByteLength]; | |
for (int x = 0, i = 0; i < input.Length; i += 2, x += 1) | |
{ | |
Bytes[x] = (byte)(HexValue[Char.ToUpper(input[i + 0]) - '0'] << 4); | |
Bytes[x] |= (byte)(HexValue[Char.ToUpper(input[i + 1]) - '0']); | |
} | |
return Bytes; | |
} | |
public string ConvertStringToHex(string input) | |
{ | |
// Take our input and break it into an array | |
char[] arrInput = input.ToCharArray(); | |
String result = String.Empty; | |
// For each set of characters | |
foreach (char element in arrInput) | |
{ | |
// My lazy way of dealing with whether or not anything had been added yet | |
if (String.IsNullOrEmpty(result)) | |
{ | |
result = String.Format("{0:X2}", Convert.ToUInt16(element)).ToString(); | |
} | |
else { | |
result += String.Format("{0:X2}", Convert.ToUInt16(element)).ToString(); | |
} | |
} | |
return result.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment