Trouble converting hex to ascii in C#
Having issues with开发者_开发问答 the code below, I get this error ...
value was either too large or to small for a character... on the line
sb.Append(Convert.ToChar(Convert.ToUInt32(hs, 16)));
for (int i = 0; i < hexString.Length - 1; i += 2)
{
String hs = hexString.Substring(i, i + 2);
sb.Append(Convert.ToChar(Convert.ToUInt32(hs, 16)));
}
Any advice new to C#?
thanks :)
Seems like your hex substring when converted to a UInt32 bit base 16 (hex), is too large (out of bounds) of the char set you're using.
Check your conversion to Uint32 and make sure that it can be converted to char indeed, meaning it's valid.
EDIT
As @Lasse points out, Substring
takes a start index and a length, but it looks like you're trying to pass it a start index and a stop index, since you're passing i + 2
to every call. This means that the first iteration will create a two-character substring, the second will be a three-character substring, and so on. Just pass 2
to it:
String hs = hexString.Substring(i, 2);
That should correct the actual problem.
While this isn't breaking anything, you should be aware that what you're doing is not converting to ASCII. ASCII is a particular character encoding, and Convert.ToChar
converts a numeric to its corresponding Unicode (UTF-16, particularly) character. As long as your values range only from 0
to 127
(00
to 7F
in hex), then you're fine for all practical purposes, since the Unicode formats share characters with the standard ASCII character set. If, however, your characters use one of the extensions onto ASCII (Latin-1, for example, which is common on Windows), then these characters will not match.
If your data is in ASCII format and you need to support values greater than 127, you can convert your hex string to a byte[]
, then pass that to the ASCIIEncoding
class to parse that data using the ASCII format:
byte[] data = new byte[hexString.Length / 2];
for(int i = 0; i < hexString.Length - 1; i += 2)
{
data[i / 2] = byte.Parse(hexString.Substring(i, 2));
}
string output = System.Text.Encoding.ASCII.GetString(data);
string assumedASCII = string.Format(@"\x{0:x4}", (int)hexString);
精彩评论