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



我有一个结构如下,它有一个指针和一个长度,我想一次将 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
}
}

我相信这是你会做的最好的事情。

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 位版本是一个微不足道的改编。

最新更新