cancel
Showing results for 
Search instead for 
Did you mean: 

concatenate 2 byte arrayes

Ala
Senior

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?

1 ACCEPTED SOLUTION

Accepted Solutions
alister
Lead

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

View solution in original post

1 REPLY 1
alister
Lead

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