Skywarth
Skywarth

Reputation: 813

Compute CRC32 of a Byte Array

In C#, I'm struggling to generate/compute CRC32. Currently I'm using this method: (Crc32 class is imported from this source)

Crc32 c = new Crc32();
var hash = string.Empty;
foreach(byte b in c.ComputeHash(package))
{
    hash += b.ToString("0x").ToLower();
}

Then:

Console.WriteLine(hash);

And the result is: 0048284b

But i want to get it in HEX form. Like "0xD754C033" so i can put it inside an byte array. Did some digging for CRC32 computation for byte array but couldn't find anything viable.

Long story short: How can i compute CRC32 hex of a byte array ? (properly)

P.S: Not duplicate according to link provided, posted answer.

Upvotes: 1

Views: 9602

Answers (1)

Skywarth
Skywarth

Reputation: 813

I found a solution which was quite fitting for my problem. In case it occurs to happen to anyone I'm posting my current approach to solve the problem. Maybe not the best but for testing purposes it does the job.

byte[] package= {255,13,45,56};
//The byte array that will be used to calculate CRC32C hex

foreach (byte b in package)
{
Console.WriteLine("0x{0:X}", b);
//Writing the elements in hex format to provide visibility (for testing)
//Take note that "0x{0:X}" part is used for hex formatting of a string. X can be changed depending on the context eg. x2, x8 etc.
}
Console.WriteLine("-");//Divider
/* Actual solution part */                
String crc = String.Format("0x{0:X}", Crc32CAlgorithm.Compute(package));
/* Actual solution part */ 
Console.WriteLine(crc);
/* Output: 0x6627634B */
/*Using CRC32.NET NuGet package for Crc32CAlgorithm class. 
Then calling Compute method statically and passing byte array to the method. Keep in mind it returns uint type value. Then writing the returned variable in hex format as described earlier. */

Mentioned Nuget Package: Crc32.NET

Upvotes: 2

Related Questions