阿里云幸运卷,戳我领取!
程序调试需要,做了一个 hex与str互转小工具方便使用
比如,输入hex 0x01与0x12,就在输入框内写 0112 (两个字节)
会输出这两个字节的ASCII:30313132 (四个字节)
需要的小伙伴自行点击下载。
初始设计操作界面如图:
代码如下:
using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace HEX与字符串转换工具
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string str = null;
int hex = 0;
if (textBox1.Text.Length % 2 == 1)
{
textBox2.Text = "输入错误!请输入2的倍数个字符!";
return;
}
for(int i = 0;i < textBox1.Text.Length;i++)
{
if((textBox1.Text[i]>='0'&& textBox1.Text[i]<='9')||
(textBox1.Text[i] >= 'a' && textBox1.Text[i] <= 'f') ||
(textBox1.Text[i] >= 'A' && textBox1.Text[i] <= 'F'))
{
hex = (int)textBox1.Text[i];
str += hex.ToString("X2");
}
else
{
str += "XX";
}
}
textBox2.Text = str;
}
private void button2_Click(object sender, EventArgs e)
{
string hexABC = "0123456789ABCDEF";
string hexabc = "0123456789abcdef";
string str = null;
byte[] buff = new byte[textBox2.Text.Length];
int i;
byte j;
if (textBox2.Text.Length % 4 != 0)
{
textBox1.Text = "输入错误!请输入4的倍数个字符!";
return;
}
for (i = 0; i < textBox2.Text.Length; i++)
{
for (j = 0; j < 16; j++)
{
if (textBox2.Text[i] == hexABC[j])
{
buff[i] = j;
break;
}
else if (textBox2.Text[i] == hexabc[j])
{
buff[i] = j;
break;
}
if (j == 15)
{
textBox1.Text = "输入错误!仅允许输入0-f!";
return;
}
}
}
int point = 0;
byte[] result = new byte[textBox2.Text.Length / 2];
for (i = 0; i < textBox2.Text.Length / 2; i++)
{
result[i] = (byte)(buff[point] * 16 + buff[point + 1]);
point += 2;
if ((result[i] >= '0' && result[i] <= '9') ||
(result[i] >= 'a' && result[i] <= 'f') ||
(result[i] >= 'A' && result[i] <= 'F'))
{
str += ((char)result[i]).ToString();
}
else
{
textBox1.Text = "输入错误!数值错误!";
return;
}
}
textBox1.Text = str;
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("https://blog.csdn.net/tiantangmoke/article/category/8920863");
}
}
}