PHP includes crc32()
and hash("crc32")
functions.
Do they have an exact counterpart in the Go runtime library ?
The actual issue
While porting (ok, rewriting) an old PHP library in Go, I had to compute a CRC
(cyclic redundancy check) checksum.
In traditional PHP, the standard function for this has been present since PHP4 :
just use the crc32 function, included in the strings
library, and check the sign bit.
For more modern code with identical results, use the
hash function found in the hash
,
library, as in this example :
|
|
No problem in sight : the Go runtime library includes a
paquet hash/crc32
package, so all should
port smoothly, should it not ?
There is just a small problem ; unlike PHP just listing the names of of its CRC algorithms on the hash_algos function page, the Go runtime library goes one step further (are you surprised yet ?) and actually documents the ones it implements, like this
|
|
Now, PHP contains no reference to the IEEE, Castagnoli, or Koopman polynomials,
just listing crc
and crc32
as a description.
The answer
Computing the values for each variation allows one to identify which polynomial actually matches :
Language | Algorithm | CRC of Hello world |
---|---|---|
PHP | crc32 | 75883905 |
PHP | crc32b | 8bd69e52 |
Go | crc32.Castagnoli | 72b51f78 |
Go | crc32.IEEE | 8bd69e52 |
Go | crc32.Koopman | b1bcb065 |
After summing a bunch of other values to ensure this was not just a chance hit, we have the expected result:
- PHP
hash(‘crc32b’, $value)
- is equivalent to Go
crc32.ChecksumIEEE(value)
.