V
V
Vlad Zaitsev2015-12-13 05:47:24
C++ / C#
Vlad Zaitsev, 2015-12-13 05:47:24

How to port the hash calculation algorithm to lua?

There is an algorithm in C:

extern uint32 HashRot13(const uint8 * str, int length)
{
    uint32 hash = 0;
    int i;
    for(i = 0; i < length; ++i, str++)
    {
        hash += (uint32)(*str);
        hash -= (hash << 13) | (hash >> 19);
    }
    return hash;
}

How to port it to Lua? Or at least tell us what it does.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
V
Vlad Zaitsev, 2015-12-14
@vvzvlad

function HashRot13(bytes)
hash = 0
for i = 1, #bytes do
hash = hash + bytes[i]
hash = bit.band(hash - bit.rol(hash, 13), 0xFFFFFFFF)
end
return bit.bswap(hash )
end

V
Vladimir Martyanov, 2015-12-13
@vilgeforce

Learn C, learn Lua. Then take and translate into one language into another.

R
Roman Mirilaczvili, 2015-12-13
@2ord

hash += (uint32)(*str);
takes a uint32 number at the current *str pointer and accumulates it in the hash variable.
perform left shift by 13 bits (multiply hash by 2^13)
perform right shift by 19 bits (divide hash by 2^19)
Bitwise OR from result of shifts above
update with subtraction from accumulated hash value

B
bromzh, 2015-12-14
@bromzh

You can take and rewrite the code from C to Lua. The trouble is that bit operations in lua out of the box suck. But there is this library (although it seems to be only for luajit).
The second and better option is to use the C++ library. Lua integrates very well with sish. If you take the usual implementation, you can write a sish module for lua. If luajit - then there is FFI out of the box , it's enough to pull the C functions.

A
abcd0x00, 2015-12-14
@abcd0x00

Or at least tell us what it does.

1. It adds an 8-bit value to a 32-bit value.
2. Then it takes the 13 bits from the left of this 32-bit value and rearranges them to the right.
3. Then the resulting 32-bit value is subtracted from the original 32-bit value.
4. Then everything repeats as long as there are 8-bit values.
If you ran this in a debugger, you would see step by step what happens in the loop.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question