2013-03-20 102 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