简体   繁体   中英

int* array to short* array conversion

This question might be silly for you guys, but I am new in C. I need to convert my int* array to short* array. Here is my sample code:

#include <stdio.h>
#include <stdlib.h>

#define file_path "/app/diag/Sound/test_gen.wav"
int main() 
{
  long data_size;
  data_size = get_file_size(file_path);

  int *data = (int *) malloc(data_size * sizeof(int));
  readPCM(data, 44100, 16, data_size);
  
  return 0;
}

Now I need to convert the data array to short* array. How can I do that? Example code would be really appreciable. I know how to do it in Java. Check out my code below.

I do know how to work it in Java. Check out my code for Java:

public static short[] encodeToSample(byte[] srcBuffer, int numBytes) {
    byte[] tempBuffer = new byte[2];
    int nSamples = numBytes / 2;        
    short[] samples = new short[nSamples];  // 16-bit signed value
    for (int i = 0; i < nSamples; i++) {
        tempBuffer[0] = srcBuffer[2 * i];
        tempBuffer[1] = srcBuffer[2 * i + 1];
        samples[i] = bytesToShort(tempBuffer);
    }
    return samples;
}
public static short bytesToShort(byte [] buffer) {
    ByteBuffer bb = ByteBuffer.allocate(2);
    bb.order(ByteOrder.BIG_ENDIAN);
    bb.put(buffer[0]);
    bb.put(buffer[1]);
    return bb.getShort(0);
}

Thanks

#include <stdio.h>
#include <stdlib.h>

#define file_path "/app/diag/Sound/test_gen.wav"
int main() 
{
  long data_size;
  data_size = get_file_size(file_path);

  int *data = (int *) malloc(data_size * sizeof(int));
  short *data2 = (short*) malloc(2 * data_size * sizeof(short)); //notice the doubled size
  readPCM(data, 44100, 16, data_size);
  for(int i = 0; i < data_size; i++)
  {
     data2[2 * i] = data[i] >> 16; // get the 16 most significant
     data2[2 * i + 1] = data[i] & 0xFFFF; //get the 16 least significant
  }
  free(data);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM