Mehdi Fanai
Mehdi Fanai

Reputation: 4059

How to Convert a float array to a byte[2] array and back java

im applying DSP effects to my raw audio input which is in byte[2] array format.To apply DSP i need to convert the byte array to float array and back.To convert byte array to float array i use the following code:

private byte[] buffer;
/*
 * 
 * Converts a byte[2] to a float, in LITTLE_ENDIAN format
 */
private float getFloat(byte argB1, byte argB2) {
    return (float) (argB1 | (argB2 << 8));
}
for (int i = 0; i < N / 2; i++) { 
    curSample[i] = getFloat(buffer[i * 2],
    buffer[i * 2 + 1]);}

I need to convert back curSample(which is a float array) to the byte[2] array.How to do that?

Upvotes: 0

Views: 1196

Answers (1)

sr01853
sr01853

Reputation: 6121

To convert byte array to float array, what you are doing does not consider the endianness.

int myInt = (byte[0] << 24) |
((byte[1] & 0xff) << 16) |
((byte[2] & 0xff) << 8) |
(byte[3] & 0xff);

or (for little-endian):

int myInt = (byte[3] << 24) |
((byte[2] & 0xff) << 16) |
((byte[1] & 0xff) << 8) |
(byte[0] & 0xff);

Then you can transform to a float using this:

float asFloat = Float.intBitsToFloat(asInt);

To convert it back to byte array

  int j=0;
  byte[] byteArray=new byte[4];
  int data=Float.floatToIntBits(asFloat);
  byteArray[j++]=(byte)(data>>>24);
  byteArray[j++]=(byte)(data>>>16);
  byteArray[j++]=(byte)(data>>>8);
  byteArray[j++]=(byte)(data>>>0);

I also find some similar information here

Upvotes: 2

Related Questions