lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Thu, Oct 24, 2019 at 4:03 AM Russell Haley <russ.haley@gmail.com> wrote:
>
> I have a working C hash function that I turned into a Lua module:
>
> int16_t crc_1021_c(int16_t old_crc, int8_t data)
> {
>     int16_t crc;
>     int16_t x;
>
>     x = ((old_crc>>8) ^ data) & 0xff;
>     x ^= x>>4;
[. . . ]
>
> Any ideas why I get a different number? All input greatly appreciated.

I _think_ (but didn't check or test)  there is an issue in your
original C code. The function crc_1021_c() and parameter old_crc
should be declared as _unsigned_ and not _signed_ short integers (ie.
uint16_t instead of int16_t.  -- parameter 'data' should also be
unsigned, but it should not make a difference.

The key issue here is that in C, I _think_ that right shift is
undefined behavior for signed integers. It is often implemented by
compilers as an _arithmetic shift_ (ie. a shift "with sign extension"
-- google arithmetic shift vs. logical shift)

Lua right shift is always a logical shift, without sign extension. So
the C line " x ^= x>>4;" and the Lua line "x = x ~ (x >> 4)" do not
compute the same result when 'x' happens to be negative.

This may explain that you get different results. As I said before, I
didn't checked.

HTH

Phil