尝试使用Convert.ToInt32
方法是需要从数字基超载:
int int32Value = Convert.ToInt32("1D", fromBase: 16);
byte byteValue = Convert.ToByte(int32Value);
我不知道,如果了解的问题。
如果你的意思是你想要的十六进制值转换为它的C#表示(“0xVALUE”),然后再补充,在所产生的十六进制字符串的开头字符:
"1D".Insert(0, "0x");
不管怎么说,我做了此功能将帮助您:
/// <summary>
/// Specifies language style to represent an Hexadecimal value
/// </summary>
public enum HexadecimalStyle : int
{
/// <summary>
/// C# Hexadecimal syntax.
/// </summary>
CSharp = 0,
/// <summary>
/// Visual Basic.Net Hexadecimal syntax.
/// </summary>
VbNet = 1
}
/// ----------------------------------------------------------------------------------------------------
/// <summary>
/// Converts an Hexadecimal value to its corresponding representation in the specified language syntax.
/// </summary>
/// ----------------------------------------------------------------------------------------------------
/// <example> This is a code example.
/// <code>
/// Dim value As String = HexadecimalConvert(HexadecimalStyle.CSharp, "48 65 6C 6C 6F 20 57")
/// Dim value As String = HexadecimalConvert(HexadecimalStyle.VbNet, "48 65 6C 6C 6F 20 57")
/// </code>
/// </example>
/// ----------------------------------------------------------------------------------------------------
/// <param name="style">
/// The <see cref="CryptoUtil.HexadecimalStyle"/> to represent the Hexadecimal value.
/// </param>
///
/// <param name="value">
/// The Hexadecimal value.
/// </param>
///
/// <param name="separator">
/// The string used to separate Hexadecimal sequences.
/// </param>
/// ----------------------------------------------------------------------------------------------------
/// <returns>
/// The resulting value.
/// </returns>
/// ----------------------------------------------------------------------------------------------------
/// <exception cref="InvalidEnumArgumentException">
/// style
/// </exception>
/// ----------------------------------------------------------------------------------------------------
[DebuggerStepThrough()]
public string HexadecimalConvert(HexadecimalStyle style, string value, string separator = "")
{
string styleFormat = "";
switch (style) {
case CryptoUtil.HexadecimalStyle.CSharp:
styleFormat = "0x{0}";
break;
case CryptoUtil.HexadecimalStyle.VbNet:
styleFormat = "&H{0}";
break;
default:
throw new InvalidEnumArgumentException(argumentName: "style", invalidValue: style, enumClass: typeof(HexadecimalStyle));
}
if (!string.IsNullOrEmpty(separator)) {
value = value.Replace(separator, "");
}
if ((value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) || (value.StartsWith("&H", StringComparison.OrdinalIgnoreCase))) {
value = value.Substring(2);
}
return string.Format(styleFormat, Convert.ToString(value).ToUpper);
}
'1D'不是'18'。它的'29'因为'D'是13.还有18将是'12' –
你确定这是你真正需要的吗? 'totalLenghtByte'是'byte',它是数字数据类型,你试图在那里存储字符串。 – Andrey
是的,我认为。我用这个来创建一个xbee框架。在xbee帧中,第3个字节是请求的长度字节。所以我计算第一行totalLenght然后将其转换为十六进制(lenght = 18 - > 1D),最后我试图将此十六进制字符串转换为字节值(十六进制:1D - >字节:0x1D) – Nethim