Home > Mobile >  How can I join the values of each array element inside a for loop together in c?
How can I join the values of each array element inside a for loop together in c?

Time:02-04

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

int main ()
{
    char *hexstring = "deadbeef"; //storing the hexadecimal value
    int i;
    unsigned int bytearray[12]; //variable to store the new output.
    uint8_t str_len = strlen(hexstring); //calculates length of the hexstring

    for (i = 0; i < (str_len / 2); i  )
     {
        sscanf(hexstring   2*i, "x", &bytearray[i]);
        printf("bytearray %d: x\n", i, bytearray[i]);
     }

    return 0;
}

Output shown currently :

bytearray 0: de
bytearray 1: ad
bytearray 2: be
bytearray 3: ef

To do: I want to merge/combine/put together the arrays such that bytearray[0] bytearray[1] bytearray[2] bytearray[3] , i.e., deadbeef output can be seen again after the for loop?

CodePudding user response:

You probably want this:

int db = 0;
for (i = 0; i < (str_len / 2); i  )
{
  db <<= 8;            // shift 8 bits to the left
  db |= bytearray[i];  // copy bytearray[i] into 8 lower bits of db
}
printf("x\n", db);
  •  Tags:  
  • Related