So I have two dynamically allocated integer variables (A and B). Each of them is of size 12 which makes each of 48 bytes. I want to transfer data from one to another in bytes basis and want to complete the transfer in 32 rounds (loops). I would describe below what I am trying to achieve:
所以我有两个动态分配的整数变量(A和B)。它们中的每一个都是12的大小,每个都是48个字节。我想以字节为基础将数据从一个传输到另一个,并希望在32轮(循环)中完成传输。我将在下面描述我想要实现的目标:
- Round 1 : First 2 Bytes (bytes 1 and 2) of array A to Array B
- 第1轮:阵列A到阵列B的前2个字节(字节1和2)
- Round 2 : Next 2 Bytes (bytes 3 and 4) of array A to array B
- 第2轮:接下来是阵列A到阵列B的2个字节(字节3和4)
Goes on transferring 2 Bytes up to round 16. In round 16, 31st and 32nd bytes would be transferred.
继续将2个字节传输到第16轮。在第16轮中,将传输第31个和第32个字节。
Then from round 17 to 32 transfer rate would be 1 Bytes/ Round, i.e.
然后从第17轮到第32轮,传输速率为1字节/圆形,即
- Round 17 : 33rd Byte from A to B
- 第17轮:从A到B的第33个字节
- Round 18 : 34th Byte from A to B
- 第18轮:从A到B的第34个字节
......
......
- Round 32 : 48th Byte from A to B
- 第32轮:从A到B的第48个字节
Below I have attached a code snippet :
下面我附上了一段代码:
int *A,*B;
A = (int *)malloc(12*sizeof(int));
B = (int *)malloc(12*sizeof(int));
for(int i= 0;i<12;i++)
A[i] = i+1;
for(int i=0;i<32;i++){
if(i<16)
//Transfer two byte from A to B in first 16 rounds, 2 bytes/round
else
// transfer 1 byte from A to B in next 16 rounds, 1 byte/round
}
free(A);
free(B);
I can understand that this might be achieved using memcpy
but I am confused in performing the address calculation. I am not sure if I am taking the correct approach. Please let me know if I am clear enough in my explanation. Any help would be very much appreciated. Thank you.
我可以理解这可以使用memcpy实现,但我在执行地址计算时感到困惑。我不确定我是否采取了正确的方法。如果我在解释中足够清楚,请告诉我。任何帮助将非常感谢。谢谢。
1 个解决方案
#1
2
You need to use char*
pointers to access individual bytes of the buffers, and uint16_t*
for the 2-byte blocks.
您需要使用char *指针来访问缓冲区的各个字节,并使用uint16_t *来表示2字节块。
char *cA = (char *)A;
char *cB = (char *)B;
uint16_t *iA = (uint16_t *)A;
uint16_t *iB = (uint16_t *)B;
for(int i=0;i<32;i++){
if(i<16) {
//Transfer two byte from A to B in first 16 rounds, 2 bytes/round
iB[i] = iA[i];
}
else {
// transfer 1 byte from A to B in next 16 rounds, 1 byte/round
cB[16 + i] = cA[16 + i];
}
}
#1
2
You need to use char*
pointers to access individual bytes of the buffers, and uint16_t*
for the 2-byte blocks.
您需要使用char *指针来访问缓冲区的各个字节,并使用uint16_t *来表示2字节块。
char *cA = (char *)A;
char *cB = (char *)B;
uint16_t *iA = (uint16_t *)A;
uint16_t *iB = (uint16_t *)B;
for(int i=0;i<32;i++){
if(i<16) {
//Transfer two byte from A to B in first 16 rounds, 2 bytes/round
iB[i] = iA[i];
}
else {
// transfer 1 byte from A to B in next 16 rounds, 1 byte/round
cB[16 + i] = cA[16 + i];
}
}