質問

I want to use intel method to calculate file crc (in c++). I found this http://create.stephan-brumme.com/crc32/ (Slicing-by-8). But this implementation return me crc32 in int, but I want to get crc32 in unsigned char[4] like in some libraries (for example cryptopp). Any idea how can I do this? Regards

役に立ちましたか?

解決

You convert your int into bytes, for example, like this:

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

Or, if you're interested in a particular endianness, you could do this:

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

or

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

Don't forget to include the appropriate headers, <string.h> and <limits.h> as applicable.

他のヒント

with something like this you could convert but it depends on little/big endian and how big your ints are.

#pragma pack(1)

#include <cstdint>

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

} crc;

crc.crc32 = yourcrc();

crc.crc4[0...3]

Simple code for little endian

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

For big endian simply the other way round

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

Assuming your int is 32bit:

unsigned int i = 0x12345678;

little endian:

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top