如何一次将32个字节复制到数组

时间:2018-09-10 19:52:24

标签: c

我有一个结构如下,它具有一个指针和一个长度,我想一次将32字节的mydata复制到32字节的数组中,不知道正确的方法是做到

typedef struct{
  void * ptr;
  size_t len;
}buf;

const uint8_t mydata[] =  {0x43, 0x54, 0x09, 0x32, 0x41, 0x45, 0x67, 0x78, 
                            0x81, 0x74, 0x67, 0x78, 0x43, 0x54, 0x09, 0x32, 
                            0x41, 0x45, 0x67, 0x78, 0x81, 0x74, 0x67, 0x78,
                            0x43, 0x54, 0x09, 0x32, 0x41, 0x45, 0x67, 0x78,
                            0x43, 0x54, 0x09, 0x32, 0x41, 0x45, 0x67, 0x78,
                            0x81, 0x74, 0x67, 0x78, 0x43, 0x54, 0x09, 0x32,
                            0x41, 0x45, 0x67, 0x78, 0x81, 0x74, 0x67, 0x78, 
                            0x43, 0x54, 0x09, 0x32, 0x41, 0x45, 0x67, 0x78};

const buf mybuf = {mydata, sizeof(mydata)};

int myfunc(buf mybuf){
   if(mybuf.len % 32 != 0){
    return -1; //checking if it is a multiple of 32 bytes
   }
   int no_myBufBytes = mybuf.len / 32; // getting how many set of 32 bytes are available

  uint8_t bytes32data[2][32]; // creating an array of 32 bytes
  for(int i = 0; i < no_myBufBytes ; i++){
   bytes32data[i][32] = mybuf.ptr + 32; // copying 32 bytes at a time
   mybuf.ptr = mybuf.ptr + 32; // moving the pointer to 32 bytes
  }
}

1 个答案:

答案 0 :(得分:1)

我相信这是您最好的选择。

void CopyChunks( uint8_t* dest, const uint8_t* src, unsigned int num )
{
    assert((((uint32_t)src)&3)==0); // data must be 32-bit aligned
    assert((((uint32_t)dest)&3)==0); // data must be 32-bit aligned

    uint32_t* d=(uint32_t*)dest;
    uint32_t* s=(uint32_t*)src;
    while( num-- )
    {
        // copy 32 bytes
        *d++=*s++;
        *d++=*s++;
        *d++=*s++;
        *d++=*s++;
        *d++=*s++;
        *d++=*s++;
        *d++=*s++;
        *d++=*s++;
    }
}

当然,这假设是32位体系结构。 64位版本是微不足道的改编。