Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

c - 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

question from:https://stackoverflow.com/questions/65866700/int-array-to-short-array-conversion

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
#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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...