Posted By

pckujawa on 07/14/10


Tagged

csharp zip dotnet crc32 crc


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Tyster


Calculate a CRC32 like the one used in zip files


 / Published in: C#
 

URL: http://www.vbaccelerator.com/home/net/code/libraries/CRC32/Crc32_zip_CRC32_CRC32_cs.asp

  1. using System;
  2. using System.IO;
  3.  
  4. namespace Vbaccelerator.Components.Algorithms
  5. {
  6. /// <summary>
  7. /// Calculates a 32bit Cyclic Redundancy Checksum (CRC) using the
  8. /// same polynomial used by Zip.
  9. /// </summary>
  10. public class CRC32
  11. {
  12. private UInt32[] crc32Table;
  13. private const int BUFFER_SIZE = 1024;
  14.  
  15. /// <summary>
  16. /// Returns the CRC32 for the specified stream.
  17. /// </summary>
  18. /// <param name="stream">The stream to calculate the CRC32 for</param>
  19. /// <returns>An unsigned integer containing the CRC32
  20. calculation</returns>
  21. public UInt32 GetCrc32(System.IO.Stream stream)
  22. {
  23. {
  24. UInt32 crc32Result;
  25. crc32Result = 0xFFFFFFFF;
  26. byte[] buffer = new byte[BUFFER_SIZE];
  27. int readSize = BUFFER_SIZE;
  28.  
  29. int count = stream.Read(buffer, 0, readSize);
  30. while (count > 0)
  31. {
  32. for (int i = 0; i < count; i++)
  33. {
  34. crc32Result = ((crc32Result) >> 8) ^ crc32Table[(buffer[i]) ^
  35. ((crc32Result) & 0x000000FF)];
  36. }
  37. count = stream.Read(buffer, 0, readSize);
  38. }
  39.  
  40. return ~crc32Result;
  41. }
  42. }
  43.  
  44. /// <summary>
  45. /// Construct an instance of the CRC32 class, pre-initialising the table
  46. /// for speed of lookup.
  47. /// </summary>
  48. public CRC32()
  49. {
  50. {
  51. // This is the official polynomial used by CRC32 in PKZip.
  52. // Often the polynomial is shown reversed as 0x04C11DB7.
  53. UInt32 dwPolynomial = 0xEDB88320;
  54. UInt32 i, j;
  55.  
  56. crc32Table = new UInt32[256];
  57.  
  58. UInt32 dwCrc;
  59. for(i = 0; i < 256; i++)
  60. {
  61. dwCrc = i;
  62. for(j = 8; j > 0; j--)
  63. {
  64. if ((dwCrc & 1)==1)
  65. {
  66. dwCrc = (dwCrc >> 1) ^ dwPolynomial;
  67. }
  68. else
  69. {
  70. dwCrc >>= 1;
  71. }
  72. }
  73. crc32Table[i] = dwCrc;
  74. }
  75. }
  76. }
  77. }
  78. }

Report this snippet  

You need to login to post a comment.