CRC32 intel实现

时间:2013-03-20 13:10:41

标签: c++ intel crc32

我想用intel方法计算文件crc(用c ++编写)。我发现了这个http://create.stephan-brumme.com/crc32/(切片8)。但是这个实现在int中返回crc32,但是我想在一些库(例如cryptopp)中使用unsigned char [4]获取crc32。知道我该怎么办? 此致

4 个答案:

答案 0 :(得分: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;
  }
}

不要忘记在适用的时候添加相应的标头<string.h><limits.h>

答案 1 :(得分:2)

有这样的东西,你可以转换,但它取决于小/大端和你的整数有多大。

#pragma pack(1)

#include <cstdint>

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

} crc;

crc.crc32 = yourcrc();

crc.crc4[0...3]

答案 2 :(得分: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);

对于big endian来说只是反过来了

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);

答案 3 :(得分:0)

假设你的int是32位:

unsigned int i = 0x12345678;
小端:

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

big endian:

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