110,538
社区成员
发帖
与我相关
我的任务
分享
string text = ScreenBox.Text;
ScreenBox.Clear();
byte[] textToByte = Encoding.Default.GetBytes(text);
for (int i = 0; i < textToByte.Length; i++)
{
byte temp = textToByte[i];
string tempHex = temp.ToString("X2") + " ";
ScreenBox.Text += tempHex;
}
string Hextext = ScreenBox.Text;
string Hextext = ScreenBox.Text;
var hexItems=Hextext.Split(' ').Where(s=>s!="").Select(s => (byte)Convert.ToInt32(s,16)).ToArray();
string value=Encoding.Default.GetString(hexItems);
///<summary>
/// 从16进制转换成汉字
/// </summary>
/// <param name="hex"></param>
/// <param name="charset">编码,如"utf-8","gb2312"</param>
/// <returns></returns>
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);
}
var hexItems=Hextext.Split(' ').Where(s=>s!="").Select(s => (byte)Convert.ToInt32(s,16)).ToArray();
[/quote]
Hextext.Split(' '):根据空格分隔字符串得到子字符串数组;
Where(s=>s!=""):筛选数组中不为空串的元素;
Select(s => (byte)Convert.ToInt32(s,16)):将序列中的元素进行类型转换并投影到新表中;
ToArray():转换成byte[]数组[/quote]
抱歉,ToArray()确实是返回byte[]型的数据,我调试时添加监视了。不知道是我自己的问题还是编译器的问题,明明是正确的参数类型,还是下划线说无效的参数类型。你的代码比楼上的朋友简洁,我采用你的方案,谢谢。
var hexItems=Hextext.Split(' ').Where(s=>s!="").Select(s => (byte)Convert.ToInt32(s,16)).ToArray();
[/quote]
Hextext.Split(' '):根据空格分隔字符串得到子字符串数组;
Where(s=>s!=""):筛选数组中不为空串的元素;
Select(s => (byte)Convert.ToInt32(s,16)):将序列中的元素进行类型转换并投影到新表中;
ToArray():转换成byte[]数组[/quote]
ToArray()返回的是int型的数组,因为前面新表返回的是int型,这样下面的GetString就不能用了。
var hexItems=Hextext.Split(' ').Where(s=>s!="").Select(s => (byte)Convert.ToInt32(s,16)).ToArray();
[/quote]
Hextext.Split(' '):根据空格分隔字符串得到子字符串数组;
Where(s=>s!=""):筛选数组中不为空串的元素;
Select(s => (byte)Convert.ToInt32(s,16)):将序列中的元素进行类型转换并投影到新表中;
ToArray():转换成byte[]数组
var hexItems=Hextext.Split(' ').Where(s=>s!="").Select(s => (byte)Convert.ToInt32(s,16)).ToArray();