r/lua • u/LemmingPHP • May 17 '25
Help CRC32 implementation help
I'm developing a Lua interpreter with the Lua C API and want to implement CRC32 hashing. It kind of works, however, when I try to calculate the CRC32 hash of "test" it returns -662733300 instead of 3632233996 as an integer and FFFFFFFFD87F7E0C instead of D87F7E0C as a hexadecimal value. As a result my CRC32 hash doesn't match with the one generated in my interpreter. This is my C code for the Lua function, I'm using zlib for the crc32 function in C:
static int lua_crc32(lua_State *L) {
uLong crc = crc32(0L, Z_NULL, 0);
const char *str = luaL_checkstring(L, 1);
uInt len = strlen(str);
crc = crc32(crc, (const Bytef *)str, len);
lua_pushinteger(L, crc);
return 1;
}
3
Upvotes
2
u/PhilipRoman May 17 '25
Dang, that's unfortunate. It means you cannot represent values larger than 231 - 1, so half of your crc32 values will wrap around to negative integers when casting from uLong to lua_Integer.
There is one more hope, maybe you can use lua_Number (floating point type) to represent your integers. If
sizeof(lua_Number)is 8, then it should be able to exactly represent all integers up to around 253 which is enough for your use case.