2013-03-20 105 views
0

我想使用英特爾方法來計算文件Crc(在C++中)。我發現這個http://create.stephan-brumme.com/crc32/(由8切成)。但是這個實現在int中返回了crc32,但是我想像在某些庫(例如cryptopp)中那樣在unsigned char [4]中獲得crc32。任何想法我怎麼能做到這一點? 問候CRC32英特爾實施

+5

重要的一點是你是否想用big endian和little endian順序的字節數。你知道嗎? – john 2013-03-20 13:12:37

+0

有什麼區別?你能告訴我怎麼用這兩種方法嗎?然後我可以計算CryptoPP中的crc,並比較結果 – januszmk 2013-03-20 13:19:12

回答

2

您將您的INT成字節,例如,像這樣:

void Uint2Uchars(unsigned char* buf, unsigned int n) 
{ 
    memcpy(buf, &n, sizeof n); 
} 

或者,如果你有興趣在一個特定的字節序,你可以這樣做:

void Uint2UcharsLE(unsigned char* buf, unsigned int n) 
{ 
    size_t i; 
    for (i = 0; i < sizeof n; i++) 
    { 
    buf[i] = n; 
    n >>= CHAR_BIT; 
    } 
} 

void Uint2UcharsBE(unsigned char* buf, unsigned int n) 
{ 
    size_t i; 
    for (i = 0; i < sizeof n; i++) 
    { 
    buf[sizeof n - 1 - i] = n; 
    n >>= CHAR_BIT; 
    } 
} 

不要忘記包含適當的標題,如適用,可以使用和<limits.h>

+0

從unsigned int轉換爲unsigned char的情況如何?以及如何使用固定大小的類型(如uint32_t等 - > cstdint.h)? – neagoegab 2013-03-20 13:20:50

+0

@neagoegab在這裏真的需要演員嗎? – 2013-03-20 13:39:09

+0

作爲替代解決方案。 – neagoegab 2013-03-21 14:45:48

2

像這樣的東西,你可以轉換,但是這取決於小/ big endian和有多大你的整數都是。

#pragma pack(1) 

#include <cstdint> 

typedef union 
{ 
    char crc4[4]; 
    uint32_t crc32; 

} crc; 

crc.crc32 = yourcrc(); 

crc.crc4[0...3] 
0

小端

int i = crc(); 
unsigned char b[4]; 
b[0] = (unsigned char)i; 
b[1] = (unsigned char)(i >> 8); 
b[2] = (unsigned char)(i >> 16); 
b[3] = (unsigned char)(i >> 24); 

大端簡單的代碼只是另一種方式圓

int i = crc(); 
unsigned char b[4]; 
b[3] = (unsigned char)i; 
b[2] = (unsigned char)(i >> 8); 
b[1] = (unsigned char)(i >> 16); 
b[0] = (unsigned char)(i >> 24); 
0

假設你的int是32位:

unsigned int i = 0x12345678; 

小尾數:

char c2[4] = {(i>>24)&0xFF,(i>>16)&0xFF,(i>>8)&0xFF,(char)i}; 

大端:

char* c = (char*)&i; 
//or if you need a copy: 
char c1[4]; 
memcpy (c1,&i,4); 
//or the same as little endian but everything reversed