我想从4字节宽的打包内存中复制一组数据(每个样本为3字节)到4字节宽并对齐4字节的内存中。
Data samples: 0x345678, 0xDEFF12, 0x689ABC, 0xABCD24
Ex: Source (each 3 byte data is packed in the 4 byte wide memory):
Add0 : 0x12345678
Add1 : 0X9ABCDEFF
Add2 : 0XABCD2468
Destination (4 bytes wide but each data is 4 byte aligned):
Add5: 0x345678
Add6: 0xDEFF12
Add7: 0x689ABC
Add8: 0xABCD24
通过memcpy实现此目的的最佳方法是什么?
答案 0 :(得分:0)
如果源和目标是数组,则下面的方法应该起作用。
#include <stdio.h>
#include <string.h>
int main()
{
unsigned int src[] = { 0x12345678, 0X9ABCDEFF, 0XABCD2468 };
unsigned int dest[4] = { 0 };
typedef unsigned char BYTE;
BYTE *pSrc = (BYTE*)(src), *pDst=(BYTE*)dest;
for (int i=0; i<4; ++i)
{
memcpy(pDst, pSrc, 3);
pSrc += 3;
pDst += 4;
}
for (int i=0; i<4; ++i)
{
printf("%x\n", dest[i]);
}
return 0;
}
输出为:
345678
deff12
689abc
abcd24