Skip to main content
Ala
Senior
November 4, 2020
Solved

concatenate 2 byte arrayes

  • November 4, 2020
  • 1 reply
  • 3021 views

hi there

I want to concatenate these 2 byte arrays

uint8_t START_BYTE[2]={0x05,0x64};

and

uint8_t disunsini[]={0x15,0x3C,0x02,0x06,0x3C,0x03,0x06,0x3C,0x04,0x06};

so I can get

{0x05,0x64,0x15,0x3C,0x02,0x06,0x3C,0x03,0x06,0x3C,0x04,0x06};

I used the code below

temp=(START_BYTE<<8)|disunsini;

but I get the error

INVALID OPERANDS TO BINARY EXPRESSION (UINT8_T * (AKA UNSIGHED CHAR*) AND INT)

why is that?

    This topic has been closed for replies.
    Best answer by alister

    There're many correct ways. Every way varies, e.g. its number of cycles for the processor to execute, its size of code, its size of data, etc. This is the simplest way, using the standard library function memcpy:

    #include <stdint.h>
    #include <string.h>
     
    int main(void)
    {
     uint8_t START_BYTE[2]={0x05,0x64};
     uint8_t disunsini[]={0x15,0x3C,0x02,0x06,0x3C,0x03,0x06,0x3C,0x04,0x06};
     uint8_t concatBuf[sizeof(START_BYTE) + sizeof(disunsini)];
     
     /* Copy START_BYTE to the start of concatBuf */ 
     memcpy(concatBuf, START_BYTE, sizeof(START_BYTE));
     /* Copy disunsini to the byte position following it */ 
     memcpy(concatBuf + sizeof(START_BYTE), disunsini, sizeof(disunsini));

    I found these on Google to explain your mistake and the operation of memcpy:

    https://www.tutorialspoint.com/cprogramming/c_bitwise_operators.htm

    https://www.tutorialspoint.com/c_standard_library/c_function_memcpy.htm

    1 reply

    alister
    alisterBest answer
    Senior III
    November 4, 2020

    There're many correct ways. Every way varies, e.g. its number of cycles for the processor to execute, its size of code, its size of data, etc. This is the simplest way, using the standard library function memcpy:

    #include <stdint.h>
    #include <string.h>
     
    int main(void)
    {
     uint8_t START_BYTE[2]={0x05,0x64};
     uint8_t disunsini[]={0x15,0x3C,0x02,0x06,0x3C,0x03,0x06,0x3C,0x04,0x06};
     uint8_t concatBuf[sizeof(START_BYTE) + sizeof(disunsini)];
     
     /* Copy START_BYTE to the start of concatBuf */ 
     memcpy(concatBuf, START_BYTE, sizeof(START_BYTE));
     /* Copy disunsini to the byte position following it */ 
     memcpy(concatBuf + sizeof(START_BYTE), disunsini, sizeof(disunsini));

    I found these on Google to explain your mistake and the operation of memcpy:

    https://www.tutorialspoint.com/cprogramming/c_bitwise_operators.htm

    https://www.tutorialspoint.com/c_standard_library/c_function_memcpy.htm