jworg
2021-06-12 13:45:20 +08:00
二楼的代码基本可以拿来直接用,就是他的 str 转 byte array 稍微错了下,我改了下,应该就是正确的内容
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace netcore
{
class Program
{
static void Main(string[] args)
{
var str = "00000048000000851001013353D5010000000000270F0133530D32303134303831333132372E302E302E3100000000000000000000000000000000000000000000001FA3";
// var data = Encoding.ASCII.GetBytes(str);
var data = StringToByteArray(str);
Console.WriteLine(data);
var result = CRC16(data, 0, data.Length);
Console.WriteLine(result);
Console.WriteLine(result.ToString("X"));
}
public static int CRC16(byte[] data, int offset, int length)
{
if (data == null || offset < 0 || offset > data.Length - 1 || offset + length > data.Length)
{
return 0;
}
int crc = 0xFFFF;
for (int i = 0; i < length; ++i)
{
crc ^= data[offset + i] << 8;
for (int j = 0; j < 8; ++j)
{
crc = (crc & 0x8000) > 0 ? (crc << 1) ^ 0x1021 : crc << 1;
}
}
return crc & 0xFFFF;
}
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
}
}