CRC32.m 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. classdef CRC32 < handle
  2. %CRC32 Class for calculating CRC32s
  3. % For Quick Reference, see http://en.wikipedia.org/wiki/Cyclic_redundancy_check
  4. % CRC32 implementation adapted from: http://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net
  5. properties (SetAccess = private, GetAccess = private)
  6. table
  7. end
  8. properties (Constant = true, GetAccess = public)
  9. DefaultPolynomial = hex2dec('edb88320');
  10. DefaultSeed = hex2dec('ffffffff');
  11. end
  12. properties (SetAccess = private, GetAccess = public)
  13. Polynomial
  14. Seed
  15. Hash
  16. end
  17. methods (Access = public)
  18. function this = CRC32(aPolynomial, aSeed)
  19. if nargin < 2
  20. aSeed = CRC32.DefaultSeed;
  21. end
  22. if nargin < 1
  23. aPolynomial = CRC32.DefaultPolynomial;
  24. end
  25. this.Polynomial = cast(aPolynomial, 'uint32');
  26. this.Seed = cast(aSeed, 'uint32');
  27. this.table = CRC32.InitializeTable(this.Polynomial);
  28. this.Initialize();
  29. end
  30. function Initialize(this)
  31. this.Hash = cast(this.Seed, 'uint32');
  32. end
  33. function crc = Compute(this, bytes, start, size)
  34. if nargin < 3
  35. start = 1;
  36. end
  37. if nargin < 4
  38. size = length(bytes) - start + 1;
  39. end
  40. crc = bitxor(... %This is Just a bitwise not
  41. CRC32.DefaultSeed,...
  42. this.CalculateHash(this.table, this.Seed, bytes, start, size));
  43. end
  44. end
  45. methods (Access = private, Static = true)
  46. function createTable = InitializeTable(aPolynomial)
  47. polynomial = cast(aPolynomial, 'uint32');
  48. createTable = cast(zeros(256, 0), 'uint32');
  49. for i = 0 : 255
  50. entry = cast(i, 'uint32');
  51. for j = 0 : 7
  52. if bitand(entry, uint32(1)) == uint32(1)
  53. entry = bitxor( (bitshift(entry, -1)) , polynomial);
  54. else
  55. entry = (bitshift(entry, -1));
  56. end
  57. end
  58. createTable(i + 1) = entry;
  59. end
  60. end
  61. function crc = CalculateHash(table, seed, buffer, start, size)
  62. crc = seed;
  63. crcspace = (1:size) + (start - 1);
  64. for i = crcspace
  65. lookup = cast( bitand(...
  66. bitxor(buffer(i) , crc), ...
  67. 255), 'uint8');
  68. crc = bitxor(...
  69. bitshift(crc , -8) , ...
  70. table(uint16(lookup) + 1));
  71. end
  72. end
  73. end
  74. end