Сложение по модулю 256 в LUA?

У меня есть строка байтов: 0x40,0x04,0x07,0x20,0x00,0x1C,0x04,0x01,0xFE,0xB0,0x00,0x70,0x07,0x00,0x00,0x81,0x00,0x00

У меня есть описание расчета контрольной суммы:
Byte #19 is the checksum. The checksum is the sum (addition) of the previous 18 bytes modulo 256.

After a few tests it appears that the checksum is for the payload part only (not including the introduction), and is the result of the simple sum of all bytes, keeping only one byte of the result (ignoring overflows). The trick is, of course, that this checksum is made by a Big Endian system, so every byte has to be reversed before being summed, then the result reversed again.


У меня есть контрольная сумма для этого набора байтов: 0х9B

Вопрос: как рассчитать эту контрольную сумму, используя lua?

Пробовал по-разному:
result = 0
bytes = {0x40,0x04,0x07,0x20,0x00,0x1C,0x04,0x01,0xFE,0xB0,0x00,0x70,0x07,0x00,0x00,0x81,0x00,0x00}
for i = 1, #bytes do 
	current_byte = bytes[i]
	for i = 1, 8 do 
		result = current_byte + result
	end
end

result = bit.bxor(0x40,0x04,0x07,0x20,0x00,0x1C,0x04,0x01,0xFE,0xB0,0x00,0x70,0x07,0x00,0x00,0x81,0x00,0x00)

result = bit.bxor(0x00,0x00,0x81,0x00,0x00,0x07,0x70,0x00,0xB0,0xFE,0x01,0x04,0x1C,0x00,0x20,0x07,0x04,0x40)

Контрольная сумма не совпадает. Как же ее все-таки посчитать?
  • Вопрос задан
  • 803 просмотра
Решения вопроса 1
vvzvlad
@vvzvlad Автор вопроса
Сам спросил, сам ответил(ну ладно, не сам, в твиттере 0leGG помог):
function HashBE(bytes)
	function rot(byte)
	    result = 0
	    for i = 0, 7 do
	        result = result + bit.lshift(bit.band(bit.rshift(byte, i), 1), 7 - i)
	    end
	    return bit.band(result, 0xFF)
	end
    hash = 0
    for i = 1, #bytes do
        hash = bit.band(hash + rot(bytes[i]), 0xFF)
    end
    return rot(hash)
end
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы