简体   繁体   English

在C中将字节数据从一个数组传输到另一个数组

[英]Transferring data in bytes from one array to another in C

So I have two dynamically allocated integer variables (A and B). 所以我有两个动态分配的整数变量(A和B)。 Each of them is of size 12 which makes each of 48 bytes. 它们每个的大小为12,即每个48个字节。 I want to transfer data from one to another in bytes basis and want to complete the transfer in 32 rounds (loops). 我想以字节为单位从一个数据传输到另一个数据,并希望在32个回合(循环)中完成传输。 I would describe below what I am trying to achieve: 我将在下面描述我要实现的目标:

  • Round 1 : First 2 Bytes (bytes 1 and 2) of array A to Array B 第一轮:阵列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, ie 那么从第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. 我可以理解使用memcpy可以实现此目的,但是在执行地址计算时感到困惑。 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. 谢谢。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM