gpt4 book ai didi

c# - 如何在C#中计算CRC_B

转载 作者:太空宇宙 更新时间:2023-11-03 11:56:35 25 4
gpt4 key购买 nike

如何按照 ISO 14443 中的描述在 C# 中计算 CRC_B 编码?以下是一些背景信息:

CRC_B encoding This annex is provided for explanatory purposes and indicates the bit patterns that will exist in the physical layer. It is included for the purpose of checking an ISO/IEC 14443-3 Type B implementation of CRC_B encoding. Refer to ISO/IEC 3309 and CCITT X.25 2.2.7 and V.42 8.1.1.6.1 for further details. Initial Value = 'FFFF'

  • 示例 1:对于 0x00 0x00 0x00,您应该以 0xCC 0xC6 的 CRC_B 结尾
  • 示例 2:对于 0x0F 0xAA 0xFF,您应该以 0xFC 0xD1 的 CRC_B 结尾

我尝试了一些随机的 CRC16 库,但它们没有给我相同的结果。我没有像 here 中那样从在线检查中得到相同的结果。 .

最佳答案

我从 ISO/IEC JTC1/SC17 N 3497 中的 C 代码中逆向了这个所以它不漂亮,但可以满足您的需求:

public class CrcB
{
const ushort __crcBDefault = 0xffff;

private static ushort UpdateCrc(byte b, ushort crc)
{
unchecked
{
byte ch = (byte)(b^(byte)(crc & 0x00ff));
ch = (byte)(ch ^ (ch << 4));
return (ushort)((crc >> 8)^(ch << 8)^(ch << 3)^(ch >> 4));
}
}

public static ushort ComputeCrc(byte[] bytes)
{
var res = __crcBDefault;
foreach (var b in bytes)
res = UpdateCrc(b, res);
return (ushort)~res;
}
}

作为测试,尝试下面的代码:

 public static void Main(string[] args) 
{
// test case 1 0xFC, 0xD1
var bytes = new byte[] { 0x0F, 0xAA, 0xFF };
var crc = CrcB.ComputeCrc(bytes);
var cbytes = BitConverter.GetBytes(crc);

Console.WriteLine("First (0xFC): {0:X}\tSecond (0xD1): {1:X}", cbytes[0], cbytes[1]);

// test case 2 0xCC, 0xC6
bytes = new byte[] { 0x00, 0x00, 0x00 };
crc = CrcB.ComputeCrc(bytes);
cbytes = BitConverter.GetBytes(crc);
Console.WriteLine("First (0xCC): {0:X}\tSecond (0xC6): {1:X}", cbytes[0], cbytes[1]);


Console.ReadLine();
}

关于c# - 如何在C#中计算CRC_B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/202466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com