Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate two byte arrays in C?

I am coding on the Arduino platform and I am trying to write something that will concatenate/append byte arrays in C.

byte a[] = {a1, ..., an};
byte b[] = {b1, ..., bm};

byte c[] = a + b; // equivalent to {a1, ..., an, b1, ..., bm}

What is the best way to get the above result?

I tried searching online, however I have not had much luck. I saw another answer on SO highlighting the steps needed in order to do this however I could not follow them. They also say that there are libraries that deal with this kind of thing, however as I am on Arduino I am unsure whether or not these are totally available to me.

I understand there needs to be some sort of memory manipulation in order for this to work however I am new to these kinds of low level manipulations so they do not make too much sense to me. I have experience in higher languages (C#, Java and some C++).


I should also add: Can the same technique work for:

byte a[] = {a1, ..., an};
byte b[] = {b1, ..., bm};

a = a + b
like image 694
Ali Caglayan Avatar asked Feb 21 '15 22:02

Ali Caglayan


People also ask

How to concatenate two bytes in C?

byte b1 = 0x5a; byte b2 = 0x25; int foo = ((int) b1 << 8) + (int) b2; now your int foo = 0x00005a25.

How do you concatenate byte arrays?

To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

What is a byte array?

A consecutive sequence of variables of the data type byte, in computer programming, is known as a byte array. An array is one of the most basic data structures, and a byte is the smallest standard scalar type in most programming languages.


1 Answers

There is no byte type in C. Unless it's some type definition, you could use unsigned char or some fixed type from <stdint.h> portably. Anyway, here is some solution:

#include <stdio.h>
#include <string.h>

int main(void) {
    unsigned char a[3+3] = {1, 2, 3}; // n+m
    unsigned char b[3]   = {4, 5, 6}; // m

    memcpy(a+3, b, 3); // a+n is destination, b is source and third argument is m

    for (int i = 0; i < 6; i++) {
        printf("%d\n", a[i]);
    }

    return 0;
}

Make sure that array a has room for at least n + m elements (here n = 3 and m = 3 as well) in order to avoid issues with array overflow (i.e. undefined behavior, that may crash yor program or even worse).

like image 191
Grzegorz Szpetkowski Avatar answered Sep 28 '22 05:09

Grzegorz Szpetkowski