阿里雲幸運卷,戳我領取!
工作經常用到,一般是打開網頁搜索在線計算工具,感覺挺麻煩,就花了幾分鐘時間自己做了一個。分享給大家~~
自己已經測試過,計算準確無誤,可放心使用~
下面附上源碼供大家學習交流
using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace 校驗計算小工具
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public byte[] StrToHex(string data)
{
byte[] result = new byte[data.Length / 2 + 100];
string hexABC = "0123456789ABCDEF";
string hexabc = "0123456789abcdef";
byte[] buff = new byte[data.Length];
int i;
byte j;
if (data.Length % 2 != 0)
{
MessageBox.Show("請輸入偶數個字符");
result[0] = 0;
return result;
}
for (i = 0; i < data.Length; i++)
{
for (j = 0; j < 16; j++)
{
if (data[i] == hexABC[j])
{
buff[i] = j;
break;
}
else if (data[i] == hexabc[j])
{
buff[i] = j;
break;
}
if (j == 15)
{
MessageBox.Show("請輸入0-f的字符");
result[0] = 0;
return result;
}
}
}
int point = 0;
for (i = 0; i < data.Length / 2; i++)
{
result[i] = (byte)(buff[point] * 16 + buff[point + 1]);
point += 2;
}
return result;
}
public string GetHex4bit(int data)
{
if (data.ToString("X2").Length == 1)
{
return "0x000" + data.ToString("X2");
}
else if (data.ToString("X2").Length == 2)
{
return "0x00" + data.ToString("X2");
}
else if (data.ToString("X2").Length == 3)
{
return "0x0" + data.ToString("X2");
}
else
{
return "0x" + data.ToString("X2");
}
}
public string checkCrc(byte[] data)
{
int crc = 0xFFFF;
int i, j;
for (j = 0; j < data.Length; j++)
{
crc = crc ^ data[j];
for (i = 0; i < 8; i++)
{
if ((crc & 0x0001) > 0)
{
crc = crc >> 1;
crc = crc ^ 0xa001;
}
else
crc = crc >> 1;
}
}
return GetHex4bit(crc);
}
public string checkSum(byte[] data)
{
int sum = 0;
for(int i =0;i< data.Length;i++)
{
sum += data[i];
}
sum = sum % 65535;
return GetHex4bit(sum);
}
private void button1_Click(object sender, EventArgs e)
{
byte[] data = new byte[textBox1.Text.Length/2];
data = StrToHex(textBox1.Text);
textBox_SUM.Text = checkSum(data);
textBox_CRC.Text = checkCrc(data);
textBox_NUM.Text = (textBox1.Text.Length / 2).ToString();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("https://blog.csdn.net/tiantangmoke/article/category/8920863");
}
}
}