C# 2.0 中的 StringToByteArray() 抛出异常
我正在VS2005上练习StringToByteArray()。但抛出异常。您能告诉我更多相关信息吗?
异常警报 **mscorlib.dll 中发生类型为“System.FormatException”的未处理异常
附加信息:找不到任何可识别的数字。**
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
// exception here
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
static void Main()
{
byte[] myByte = new byte[2];
myByte = StringToByteArray("0x0");
}
I am practicing StringToByteArray() on VS2005. But throw exception. Could you please tell me more information about it?
Exception alert **An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Could not find any recognizable digits.**
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
// exception here
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
static void Main()
{
byte[] myByte = new byte[2];
myByte = StringToByteArray("0x0");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要从传入的字符串开头删除“0x”,或者使用
int i = 2;
启动for
循环。您还在方法中分配数组。您也不需要在Main
中执行此操作。You either need to drop the "0x" from the start of the string you pass in, or start your
for
loop withint i = 2;
. Also you're allocating the array in your method. You don't need to do itMain
as well.好吧,你有可能出现被零除的异常...
修复该问题后,你需要通过确保你的字符串以 0x 开头来继续输入验证,然后在进行转换时跳过前缀。
Well, you have the possibility of a divide by zero exception...
After you fix that, you need to continue your input validation by ensuringing that your string starts with 0x and then skip the prefix when you do your conversion.