Mehmet Berk Cetin
Mehmet Berk Cetin

Reputation: 121

How to convert an int8_t array to int32_t array in C

I have an array and I want to convert it to an int32_t array.

I tried the code below.

int32_t const_data[11];
int8_t buffer[44];

    int k = 0;
    while (k < 11) {
        for (int j = 0; j < 44; j++) {
                const_data[k] = bf.buffer[j];
                k++;
        }
    }

Upvotes: 3

Views: 2846

Answers (2)

bigwillydos
bigwillydos

Reputation: 1371

The easiest and most straight forward way is to use a union

#define array_size_int32    11
#define array_size_int8     44

typedef union{
    int32_t const_data[array_size_int32];
    int8_t buffer[array_size_int8];
}my_union_t;

Example usage:

/* initialize union members */
my_union_t my_union = {
    .const_data = {
        0x12345678,
        0x12345678,
        0x12345678,
        0x12345678,
        0x12345678,
        0x12345678,
        0x12345678,
        0x12345678,
        0x12345678,
        0x12345678,
        0x12345678,
    },
};

Example way to print:

uint8_t i;

for(i = 0; i < array_size_int8; i++){

    /* mask off sign extension bits */
    printf("my_union.buffer[%d] = %x\n", i, my_union.buffer[i] & 0xff);

}

You can try the code out here

EDIT:

I should add that this works because the memory size needed to allocate either array is the same and you'll run in to problems if you change the #define's without taking that in to consideration.

For example,

#define array_size_int32    10    //40 bytes
#define array_size_int8     45    //45 bytes

Upvotes: 4

Manthan Tilva
Manthan Tilva

Reputation: 3277

Below is solution which I used in past for similar problem.

#include <stdio.h>
#include <inttypes.h>
int main(){
    int8_t input[] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08};
    int32_t output[10];
    int count=0;
    for(;count<sizeof(input);count+=sizeof(int32_t)/sizeof(int8_t)){
        output[count] = (int32_t)(*(int32_t*)(&input[count]));
        printf("%x:%x\n",input[count],output[count]);
    }
    return 0;
}

Note: As pointed out by @tadman in comment. You also need to consider endianness of your platform. This solution works well for my problem on platform I was working. Based on your platform you may need to tweak this.

Live Code

Upvotes: -1

Related Questions