0

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?

1
  • 1
    Float is a 32 bit value, how it is so you convert into it from just two bytes? Probably you should use floatToIntBits to convert float into byte array. Commented Jan 25, 2013 at 11:35

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

and after Applying some DSP to the asFloat...How can i convert back the Float to the byte?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.