1

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.

Skywarth
  • 623
  • 2
  • 9
  • 26
  • WHy dont you use microsoft CNG Api – Code Name Jack Jul 26 '19 at 11:27
  • 1
    Possible duplicate of [byte\[\] to hex string](https://stackoverflow.com/questions/623104/byte-to-hex-string) – Robert Jul 26 '19 at 11:28
  • `c.ComputeHash(package)` looks like it returns a byte array. If you want to "put it inside an byte array", you've already got one... the return value of `c.ComputeHash(package)` – spender Jul 26 '19 at 11:38
  • It's not at all clear what you're asking for here, and the answer you provided just confuses things more. – Jim Mischel Jul 26 '19 at 15:47

1 Answers1

2

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

Skywarth
  • 623
  • 2
  • 9
  • 26