This question looks like a bunch of other questions, but none exactly match what I need. The problem with the other related questions seem to do an implicit conversion to decimal based on Visual Studio's IntelliSense.
Goal: Trying to convert hex string to byte array of hex values (not decimal values) in C#.
public static byte[] ConvertHexValueToByteArray()
{
string hexIpAddress = "0A010248"; // 10.1.2.72 => "0A010248"
byte[] bytes = new byte[hexIpAddress.Length / 2];
for (int i = 0; i < hexIpAddress.Length; i += 2)
{
string s2CharSubStr = hexIpAddress.Substring(i, 2); // holds "0A" on 1st pass, "01" on 2nd pass, etc.
if ((s2CharSubStr.IsAllDigit()) && (int.Parse(s2CharSubStr) < 10)) // fixes 0 to 9
bytes[i / 2] = (byte) int.Parse(s2CharSubStr); // same value even if translated to decimal
else if (s2CharSubStr.IsAllDigit()) // fixes stuff like 72 (decimal) 48 (hex)
bytes[i / 2] = Convert.ToByte(s2CharSubStr, 10); // does not convert, so 48 hex stays 48 hex. But will not handle letters.
else if (s2CharSubStr[0] == '0') // handles things like 10 (decimal) 0A (hex)
bytes[i / 2] = // ?????????????????????????????
else // handle things like AA to FF (hex)
bytes[i / 2] = // ?????????????????????????????
}
return bytes;
}
Answers like the two below do implicit conversions (as viewed in Visual Studio's IntelliSense) from the hex to decimal AND/OR fail to handle the alpha part of the hex: 1)
bytes[i / 2] = (byte)int.Parse(sSubStr, NumberStyles.AllowHexSpecifier);
2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
3) bytes[i / 2] = Convert.ToByte(hexIpAddress.Substring(i, 2));
So I would like the function to return the equivalent of this hard-coded byte array:
byte[] currentIpBytes = {0x0A, 01, 02, 0x48};
bytevalue is abytevalue...sobytes[0]will be of value10(decimal) which is0x0A. What other value do you wantbytes[0]to have?bytes[i/2] = Convert.ToByte(hexIpAddress.Substring(i,2));does exactly what you want. (though it's0x48, not48)