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

Asked

Viewed 54 times

0

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

Can anyone help me, pfv? Thank you

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];

Follow 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;
}

Exit:

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 
  • Thank you so much! As I am a beginner in C, I feel a little lost. Thank you again.

  • I saw your pi! Very good xD

Browser other questions tagged

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