"Merge" elements of a single vector

Asked

Viewed 681 times

3

I have a vector with four elements that are numbers represented in hexadecimal form.

What I need to do is concatenate these four elements (I believe that this is not the right word, but I have not found a better one)?

For example:

int v[4]={0xA, 0xBB, 0x4B, 0x18};

I need a result that is similar to:

int resultado=0xABB4B18;

2 answers

4


It has one form only to print and another that really calculates correctly and prints:

#include <stdio.h>

int main(void) {
    int v[4] = {0x0A, 0xBB, 0x4B, 0x18};
    for (int i = 0; i < 4; i++) printf("%02X", v[i]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

#include <stdio.h>

int main(void) {
    int v[4] = {0x0A, 0xBB, 0x4B, 0x18};
    int resultado = 0;
    for (int i = 0; i < 4; i++) {
        resultado *= 256;
        resultado += v[i];
    }
    printf("%08X", resultado);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • The first printf should be zeroed (at least for bytes from the second): printf(i?"%02X":"%X", v[i]);

  • @pmg indeed both could have this formatting, is done.

3

Well, if you multiply a number in HEXA by 100 in HEXA, you "shift" to the right.

For example:

in DECIMAL -> 13 * 100 = 1300
in HEXADEC -> 0x13 * 0x100 = 0x1300

Try applying this concept to "concatenate" the values in HEXA.

Another example:

If A = 0xE3, B = 0x4C, then A*0x100 + B = 0xE34C.

Browser other questions tagged

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