C# 将字符串0x255转换为字节时出现System.OverflowException

C# 将字符串0x255转换为字节时出现System.OverflowException,c#,byte,C#,Byte,我不知道为什么我会得到它。。。你知道为什么吗 代码: data[i] = Convert.ToByte(build, 16); 例如,build是一个值为0x255的string字符串,其他转换对我来说工作正常0x04。它只是停留在那个值上十六进制值从0x00到0xFF(0-255) 因此0x255不作为字节存在。您要查找的值而不是0x255是0xFF您正在混合使用十进制和十六进制: 请注意 0x04 (hex) == 4 and that's why you have a correc

我不知道为什么我会得到它。。。你知道为什么吗

代码:

data[i] = Convert.ToByte(build, 16);

例如,
build
是一个值为0x255
string
字符串,其他转换对我来说工作正常0x04。它只是停留在那个值上

十六进制值从
0x00
0xFF
(0-255)

因此
0x255
不作为字节存在。您要查找的值而不是
0x255
0xFF

您正在混合使用十进制和十六进制:

请注意

0x04  (hex) == 4   and that's why you have a correct result
在您的情况下,代码应该是

// build == "255" and build is decimal
data[i] = Convert.ToByte(build, 10);


它应该是
0xFF
,而不是
0x255
(这是一个字节范围:
0x255==597
)再看一看关于@DmitryBychenko的文档谢谢你!。解决了它;)
// build == "255" and build is decimal
data[i] = Convert.ToByte(build, 10);
// build is hexadecimal, but "0x255" is an incorrect value
build = "0xFF";
...
data[i] = Convert.ToByte(build, 16);