You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何将文本框的HEX字符串转换为byte数组中的字节值?

解决C#中带0x前缀的十六进制字符串转byte问题

你遇到的FormatException是因为Convert.ToByte()的默认重载只能解析十进制字符串,不识别0x开头的十六进制格式标记。下面给你两种可行的解决办法:

方法1:移除0x前缀后转换

先把字符串里的0x前缀去掉,再调用Convert.ToByte()并指定十六进制基数(参数16):

string byte3 = "0x50";//value from textBox at runtime
string byte4 = "0xEF";//value from textBox at runtime

// 移除0x前缀
string cleanedByte3 = byte3.Replace("0x", "");
string cleanedByte4 = byte4.Replace("0x", "");

byte[] bytes = new byte[5];
bytes[0] = 0xAB; //hard coded value
bytes[1] = 0x0F; //hard coded value
bytes[2] = 0x02; //hard coded value
bytes[3] = Convert.ToByte(cleanedByte3, 16); // 指定十六进制解析
bytes[4] = Convert.ToByte(cleanedByte4, 16);

void ThenIUseTheBytesArrayInAnotherMethod(byte[] bytes){
    // 你的业务逻辑
}

方法2:用byte.Parse指定格式

直接使用byte.Parse(),通过NumberStyles.HexNumber参数让方法识别带0x前缀的十六进制字符串:

using System.Globalization; // 需要引入这个命名空间

string byte3 = "0x50";//value from textBox at runtime
string byte4 = "0xEF";//value from textBox at runtime

byte[] bytes = new byte[5];
bytes[0] = 0xAB; //hard coded value
bytes[1] = 0x0F; //hard coded value
bytes[2] = 0x02; //hard coded value
bytes[3] = byte.Parse(byte3, NumberStyles.HexNumber);
bytes[4] = byte.Parse(byte4, NumberStyles.HexNumber);

void ThenIUseTheBytesArrayInAnotherMethod(byte[] bytes){
    // 你的业务逻辑
}

额外建议

实际从文本框取值时,建议加输入验证逻辑,避免用户输入无效格式导致报错:

  • 检查字符串是否以0x开头
  • 验证剩余部分是否为合法的十六进制字符(0-9、A-F/a-f)
  • 用try-catch包裹转换代码,捕获格式错误并提示用户

内容的提问来源于stack exchange,提问作者Buvag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 04:05:13