我有我想轉換到LUA C函數,但我得到了奇怪的結果出來的Lua:C到Lua的轉換 - 怪異的結果
unsigned short crc16(const char* pstrCurrent, int iCount)
{
unsigned short wCRC = 0;
int iIndex = 0;
while(--iCount >= 0)
{
wCRC = wCRC^((int)(*pstrCurrent++) << 8);
printf ("WCRC = %u\n", wCRC);
}
return (wCRC & 0xFFFF);
}
,這裏是我如何開始的Lua:
local function crc16(keyCurrent, byteCount)
wCRC = 0
byteIndex = 1
local crcInput = {}
while byteCount > 0 do
print ("BYTE COUNT= " .. byteCount)
wCRC=bit32.bxor(wCRC, bit32.lshift(keyCurrent[byteIndex], 8))
print ("WCRC = " .. wCRC)
byteCount = byteCount-1
byteIndex = byteIndex+1
end
end
是的,我知道C函數是不完整的,我只是想比較是什麼造成的問題。
WCRC的打印是C和Lua爲相同的輸入打印完全不同的數字。
我的Lua轉換不正確?這是我第二次或第三次使用Lua,所以我不太確定自己做錯了什麼。
***************** UPDATE ********************
因此,這裏是全C和LUA和一個小巧的測試代碼:
unsigned short crc16(const char* pstrCurrent, int iCount)
{
unsigned short wCRC = 0;
int iIndex = 0;
// Perform the following for each character in the buffer
while(--iCount >= 0)
{
// Get the byte information for the calculation and
// advance the pointer
wCRC = wCRC^((int)(*pstrCurrent++) << 8);
for(iIndex = 0; iIndex < 8; ++iIndex)
{
if(wCRC & 0x8000)
{
wCRC = (wCRC << 1)^0x1021;
}
else
{
wCRC = wCRC << 1;
}
}
}
return (wCRC & 0xFFFF);
}
和LUA轉換:
function crc16 (keyCurrent, iCount)
wCRC = 0
byteIndex = 1
iIndex = 0
local crcInput = {}
while iCount >= 1 do
wCRC = bit32.bxor (wCRC, bit32.lshift(keyCurrent[byteIndex], 8))
for iIndex=0,8 do
if (bit32.band (wCRC, 0x8000) ~= nil) then
wCRC = bit32.bxor (bit32.lshift (wCRC, 1), 0x1021)
else
wCRC = bit32.lshift (wCRC, 1)
end
end
iCount = iCount-1
byteIndex = byteIndex+1
end
return (bit32.band (wCRC, 0xFFFF))
end
local dKey = {}
dKey = {8, 210, 59, 0, 18, 166, 254, 117}
print ("CRC = " .. crc16 (dKey ,8))
在C中,對於相同的陣列獲得:CRC16 = 567
在LUA,我得到:CRC = 61471
有人能告訴我我做錯了什麼嗎?
感謝
什麼輸入和兩種語言的輸出是什麼? –