0

I'd like to translate mssql binary_checksum from c# to Lua, but i'm a newbie in Lua...

private static int SQLBinaryChecksum(string text)
{
    long sum = 0;
    byte overflow;
    for (int i = 0; i < text.Length; i++)
    {
        sum = (long)((16 * sum) ^ Convert.ToUInt32(text[i]));
        overflow = (byte)(sum / 4294967296);
        sum = sum - overflow * 4294967296;
        sum = sum ^ overflow;
    }

    if (sum > 2147483647)
        sum = sum - 4294967296;
    else if (sum >= 32768 && sum <= 65535)
        sum = sum - 65536;
    else if (sum >= 128 && sum <= 255)
        sum = sum - 256;

    return (int)sum;
}
Egor Skriptunoff
  • 906
  • 1
  • 8
  • 23
Reminus
  • 1
  • 1
  • where is the Lua? and what is the question? is it failing to compile? is it giving an unexpected answer? if it is giving an unexpected answer, where does your *expected* answer come from? Is it throwing an exception? if so: what exception? is it perhaps something about "invalid format"? *what?* – Marc Gravell Mar 29 '18 at 13:48
  • Could you include your attempt at translating it and how it's failing? – mech Mar 29 '18 at 13:49
  • woah... are you asking us to convert this to Lua for you? if so... have you tried first? – Marc Gravell Mar 29 '18 at 13:50

1 Answers1

0

You didn't specify your version of Lua, so I've made a suggestion that you are using LuaJIT.

-- Works only on LuaJIT
function SQLBinaryChecksum(text)
   local sum = 0
   for i = 1, #text do
      sum = bit.bxor(bit.rol(sum, 4), text:byte(i))
   end
   if sum >= 32768 and sum <= 65535 then
      sum = sum - 65536
   elseif sum >= 128 and sum <= 255 then
      sum = sum - 256
   end
   return sum
end
-- Did you notice that Lua code is shorter than C#?

This code may work incorrectly if text contains characters beyond ASCII.
To fix this I should know the correct checksum of string

Egor Skriptunoff
  • 906
  • 1
  • 8
  • 23