C#string转化成16进制int

2025-03-03 19:32:40
推荐回答(5个)
回答1:

///


/// 从汉字转换到16进制
///

///
/// 编码,如"utf-8","gb2312"
/// 是否每字符用逗号分隔
///
public static string ToHex(string s, string charset, bool fenge)
{
if ((s.Length % 2) != 0)
{
s += " ";//空格
//throw new ArgumentException("s is not valid chinese string!");
}
System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
byte[] bytes = chs.GetBytes(s);
string str = "";
for (int i = 0; i < bytes.Length; i++)
{
str += string.Format("{0:X}", bytes[i]);
if (fenge && (i != bytes.Length - 1))
{
str += string.Format("{0}", ",");
}
}
return str.ToLower();
}
///
/// 从16进制转换成汉字
///

///
/// 编码,如"utf-8","gb2312"
///
public static string UnHex(string hex, string charset)
{
if (hex == null)
throw new ArgumentNullException("hex");
hex = hex.Replace(",", "");
hex = hex.Replace("\n", "");
hex = hex.Replace("\\", "");
hex = hex.Replace(" ", "");
if (hex.Length % 2 != 0)
{
hex += "20";//空格
}
// 需要将 hex 转换成 byte 数组。
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
try
{
// 每两个字符是一个 byte。
bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
System.Globalization.NumberStyles.HexNumber);
}
catch
{
// Rethrow an exception with custom message.
throw new ArgumentException("hex is not a valid hex number!", "hex");
}
}
System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
return chs.GetString(bytes);
}

汉子的话使用gb2312

回答2:

16进制到10进制?
//十进制转二进制
Convert.ToString(69, 2); //69为被转值
//十进制转八进制
Convert.ToString(69, 8); //69为被转值
//十进制转十六进制
Convert.ToString(69, 16); //69为被转值
//二进制转十进制
Convert.ToInt32(”100111101″, 2); //100111101为被转值
//八进制转十进制
Convert.ToInt32(”76″, 8); //76为被转值
//C# 16进制转换10进制
Convert.ToInt32(”FF”, 16); //FF为被转值

回答3:

int ReAsc = Convert.ToUInt16(ReHex);
returnStr = Encoding.GetEncoding("GBK").GetString(Str);

private string asctostr(String tmpStr)
{
String returnStr = "";
String str = tmpStr;
if (str == "")
return "";
int i = 0;
int j = 0;
int partflg = 2;
byte[] Str = new byte[(int)str.Length / 2];
while (i < str.Length)
{
String ReHex = str.Substring(i, i + partflg);
int ReAsc = Convert.ToUInt16(ReHex);
Str[j] = (byte)ReAsc;
i += partflg;
j++;
}
try
{
returnStr = Encoding.GetEncoding("GBK").GetString(Str); //new String(Str, "GBK");
}
catch (Exception e)
{

}
return returnStr;
}

回答4:

我学的是c#,你是要转换类型是不是?是的话把要把什么值转换成什么类型说一下,我看不懂你给出的代码写的是什么···

回答5:

string str = "0x1A";
int x = Convert.ToInt32(str, 16);
Console.WriteLine(x);