"Compress" values from an array of shorts, to an array of integers

0

Good evening. I have to work out an evaluation exercise in which I have no idea how to do it. I have to compress 2 consecutive values of an array of shorts, to be stored in an array of integers. This is done until the end of the shorts array. (exercise in C)

Can anyone help me, pfv? Thank you

    
asked by anonymous 06.10.2017 / 22:05

1 answer

2

You can do something like:

short a[ ARRAY_MAX_TAM * 2 ];
int b[ ARRAY_MAX_TAM ];

for( i = 0; i < ARRAY_MAX_TAM * 2; i++ )
    ((short*)b)[i] = a[i];

Here is a tested code that can solve your problem:

#include <stdio.h>

/* Quantidade de elementos na array de inteiros */
#define ARRAY_MAX_TAM   (10)

/* Array de shorts */
short a[ ARRAY_MAX_TAM * 2 ] = { 3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8,4 };

int main( void )
{
    int i = 0;
    int b[ ARRAY_MAX_TAM ]; /* Array de inteiros */

    /* Converte array de shorts para ints */
    for( i = 0; i < ARRAY_MAX_TAM * 2; i++ )
        ((short*)b)[i] = a[i];

    /* Exibe Array de shorts */
    for( i = 0; i < ARRAY_MAX_TAM * 2; i++ )
        printf("%d ", a[i] );
    printf("\n");

    /* Exibe Array de inteiros */
    for( i = 0; i < ARRAY_MAX_TAM; i++ )
        printf("%d ", b[i] );
    printf("\n");

    return 0;
}

Output:

3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 
65539 65540 589829 393218 196613 524293 458761 196617 196610 262152 
    
06.10.2017 / 23:04