Concatenate variables into C

Asked

Viewed 132 times

2

It is possible to concatenate 2 variables of different types and obtain a single variable that occupies the same bytes as the sum of the bytes of the 2 variables of different types?

For example:

short int A=9999;
unsigned char B=110;

And get a C variable that takes 3 bytes and contains 9999110.

  • You can use struct + Union, just take care of the endianness of the system used to leave in the right order. Only that joining the bytes does not give that you said, it would be another value. 9999110 is not 9999 + 110 concatenation, do not confuse digits with bytes

  • No, the basic data types of the C language have predetermined size. In addition the concatenation operation is defined for strings and not for other data types.

1 answer

3


There is how to do what you asked, but the result is probably not what you expect.

  • To declare a structure in C, you have the struct (which is literally structure);

  • To make two members point to the same memory space, you have the union (union).

You can use both, and for that I made an example. In this case, so that the int and the char "coubessem" in another variable, I needed a "pad" (padding), to give the four bytes of the double used in the example.


Putting into practice:

See the code:

#include <stdio.h>

union {
    struct  {
        short int A;
        unsigned char B;
        unsigned char pad; // só para ficar com 4 bytes, igual o long a seguir
    };
    long result; // Por estarem dentro de uma Union, tanto a struct acima
                 // quanto o long estarão no mesmo espaço.
                 // São nomes diferentes para o mesmo dado
                 // (ou partes dele no caso de A e B.

} x;

int main(void) {
    x.A = 0x8899;  // Usei hexadecimal para ficar evidente o funcionamento
    x.B = 0xCC;    // E propositalmente pus em maiúscula para diferir do resultado
    x.pad = 0;
    printf("%x",x.result);
}

Upshot:

cc8899

See working on IDEONE.

Depending on the "endianness" of the environment, it could have been reversed the order of bytes. Then you have to better understand the concept if you are going to work with hybrid environments.


Completion

The good part is you know you can concatenate bytes in C memory and take a "variable" only (in this case a struct member).

The bad news is that bytes behave like bytes, and in no way resemble the concatenation of decimal digits (which is a human thing, for the machine what matters is the power of 2).

In hexadecimal you clearly see that the bytes have joined together, but if you try to use decimals, you may find the result strange when displaying in "human" notation (decimal).


Further reading:

How hexadecimal numbers work?

What is big-endian and what is the difference to little-endian?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.