Reputation: 361
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};
Upvotes: 0
Views: 15562
Reputation: 276
private string DateToHex(DateTime theDate)
{
string isoDate = theDate.ToString("yyyyMMddHHmmss");
string resultString = string.Empty;
for (int i = 0; i < isoDate.Length ; i++) // Amended
{
int n = char.ConvertToUtf32(isoDate, i);
string hs = n.ToString("x");
resultString += hs;
}
return resultString;
}
Upvotes: 1
Reputation: 43876
string hexIpAddress = "0A010248"; // 10.1.2.72 => "0A010248"
byte[] bytes = new byte[hexIpAddress.Length / 2];
for (int i = 0; i < hexIpAddress.Length; i += 2)
bytes[i/2] = Convert.ToByte(hexIpAddress.Substring(i, 2), 16);
This results in this array:
bytes = {0x0A, 0x01, 0x02, 0x48};
or represented as decimals:
bytes = {10, 1, 2, 72};
or as binaries 00001010
, 000000001
, 00000010
, 01001000
(binary literals are still not supported in C#6).
The values are the same, there is no representation in any base in byte
. You can only decide how the values should be represented when converting them to strings again:
foreach(byte b in bytes)
Console.WriteLine("{0} {0:X}", b);
results in
10 A
1 1
2 2
72 48
Upvotes: 3