建立 crc32.cpp
代码如下:
---------------------------------------------------------------------------------
//kwanhong young 2004-9-1
unsigned long crctable[256];
/*
int main(int argc, char* argv[])
{
init();
unsigned long r=update((unsigned char *)("abcdefg"), 7,0xffffffff);
printf("result is:%d",r);
return 0;
}
*/
//void init()
extern "c" void __stdcall init()
{
unsigned long crc, i, j;
unsigned long poly = 0xedb88320;
for(i=0; i<256; i++)
{
crc = i;
for(j=8; j>0; j--)
{
if(crc & 1)
crc = (crc >> 1) ^ poly;
else
crc >>= 1;
}
crctable[i] = crc;
}
}
extern "c" unsigned long __stdcall update(unsigned char *buffer,long length, unsigned long crc)
{
//unsigned long crc = 0xffffffff;
unsigned char *ptr = buffer;
while(length > 0)
{
crc = ((crc >> 8) & 0x00ffffff) ^ crctable[(crc ^ *ptr) & 0xff];
ptr++;
length--;
}
return crc;
}
创建 crc32.def
代码如下:
---------------------------------------------------------------------------
exports
init
update
然后就可以编译成 dll 了。
现在用vb新建一个 class。代码如下:
-------------------------------------------------------------------------
private declare sub crc32init lib "kw_crc32.dll" alias "init" ()
private declare function crc32update lib "kw_crc32.dll" alias "update" (db as any, byval length as long, byval crcvalue as long) as long
private m_lvalue as long
private sub class_initialize()
'//make crc32 table
crc32init
m_lvalue = &hffffffff
end sub
public sub reset()
m_lvalue = &hffffffff
end sub
public sub encode(bytdata() as byte, byval ilen as long)
m_lvalue = crc32update(bytdata(0), ilen, m_lvalue)
end sub
public sub encodeptr(byval ptbytdata as long, byval ilen as long)
'//use data pointer
m_lvalue = crc32update(byval ptbytdata, ilen, m_lvalue)
end sub
public function getvalue() as string
getvalue = right("00000000" & hex$(m_lvalue xor &hffffffff), 8)
end function
public function encodestring(sourcestring as string) as string
'// function to digest a text string and output the result as a string
'// of hexadecimal characters.
dim bytdata() as byte
m_lvalue = &hffffffff
if len(sourcestring) = 0 then
redim bytdata(0)
encodestring = "00000000"
else
bytdata = strconv(sourcestring, vbfromunicode)
m_lvalue = crc32update(bytdata(0), ubound(bytdata) + 1, m_lvalue)
end if
encodestring = right("00000000" & hex$(m_lvalue xor &hffffffff), 8)
end function
public function savestate() as string
'//save the state
savestate = m_lvalue
end function
public function loadstate(s as string) as boolean
'//load the state
m_lvalue = s
loadstate = true
end function
现在就可以在vb里面实现高速的crc32 运算。