optional start and length parameters by Crc16Ccitt.CalculateMsb1021: S.Z, T.W - 18.07.2024

This commit is contained in:
Stoyan Zlatev
2024-07-18 13:06:59 +02:00
parent f563cee2f0
commit 53fce0c363
+47 -3
View File
@@ -112,13 +112,29 @@ namespace Xylem.Common.Utils.Crc16Ccitt
/// </summary>
/// <param name="data">data to be processed</param>
/// <returns>Calculated CRC</returns>
public static UInt16 CalculateMsb1021(Byte[] data)
public static UInt16 CalculateMsb1021(Byte[] data, Int32 start = 0, Int32 length = 0)
{
var crc = CrcSeedFfff;
foreach (var t in data)
var dataLength = data.Length;
if (length <= 0)
{
length = dataLength;
}
if (dataLength < length)
{
length = dataLength;
}
var crc = CrcSeedFfff;
for (var b = start; b < length; b++)
{
var t = data[b];
//copy data byte to higher word because of MSB will be XORed
var dataWord = (UInt16)((t << 8) & 0xFF00);
for (var i = 0; i < 8; i++)
{
//test if CRC highest bit or data input highest bit is XORed set to one
@@ -136,8 +152,36 @@ namespace Xylem.Common.Utils.Crc16Ccitt
dataWord <<= 1; //MSB first shifted out
}
}
//foreach (var t in data)
//{
// //copy data byte to higher word because of MSB will be XORed
// var dataWord = (UInt16)((t << 8) & 0xFF00);
// for (var i = 0; i < 8; i++)
// {
// //test if CRC highest bit or data input highest bit is XORed set to one
// if (0x8000 == ((crc ^ dataWord) & 0x8000)) //shifted in MSB first
// {
// //shift CRC high bit out
// crc <<= 1;
// //apply generator polynomial
// crc ^= CrcGp1021;
// }
// else //CRC highest bit and data input highest bit is equal
// {
// crc <<= 1;
// }
// dataWord <<= 1; //MSB first shifted out
// }
// }
return crc;
}
public static Byte[] CalculateCRC1021LSBFirst(Byte[] bytes, Int32 start, Int32 length)
{
var crc = CalculateMsb1021(bytes, start, length);
return BitConverter.GetBytes(crc);
}
/// <summary>
/// Calculates the CRC (LSB first, CRCCCITT 0x0408) from a data array of bytes.