简体   繁体   English

将十六进制字符串转换为 C# 中的字节

[英]Convert a hex string to a byte in C#

I have a String like this:我有一个这样的字符串:

String data = "0x0f";

and I would like to leave it as a single byte which represents this hex.我想将它保留为代表此十六进制的单个字节。 Does anyone know what function I can use?有谁知道我可以使用什么 function?

I tried using the following function:我尝试使用以下 function:

public byte pegarValorHexText(string text)
{
    int NumberChars = text.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(text.Substring(i, 2), 16);
    return bytes[0];
}

The string has a hexadecimal value, it has a maximum of 4 characters, the sequence "0x" indicating that it is a hexadecimal value and a sequence of two hex chars该字符串有一个十六进制值,它最多有 4 个字符,序列“0x”表示它是一个十六进制值和两个十六进制字符的序列

Just use Convert.ToByte then, it should handle the hex prefix:然后使用Convert.ToByte ,它应该处理十六进制前缀:

byte b = Convert.ToByte("0x0f", 16); // 15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM