2

Let's say that on Android (Java) we have a byte array that represents a sequence of 16-bit signed integers.

I am needing to be able to decode the values from this array by using a for-loop and concatenating each pair of bytes to retrieve the original value back again (Please don't suggest a different method such as a ByteBuffer).

In order to test my algorithm, I want to encode and decode a list of ints and see if I get the same numbers back.

However, I can't figure out how to encode the original list of ints into a byte array for testing purposes. I don't want to simply reverse my algorithm because I don't know if it works yet... I would be open to using ByteBuffer or any other known-good means to do the encoding because it's only for testing/simulation purposes -- in the real app, the byte array is already encoded by Android.AudioRecord.

    // dec : short : byte a : byte b
    // 4536 : 0001000100000100 : 17 : 4
    // -1 : 1111111111111111 : -1 : -1
    // -32768 : 1000000000000000 : -128 : 0 
    // 32767 : 1000000000000001 : -128 : 1
    // 0 : 0000000000000000 : 0 : 0
    // -2222 : 1111011101010010 : -9 : 82

void _go() {
        
        int[] source = {4536,-1,-32768,32767,0,-2222};

        // is this even correct?
        byte[] expectedEncoding = {17,4,-1,-1,-128,0,-128,1,0,0,-9,82};

        byte[] encoded = ??? // <----- what goes here?

        int[] decoded = new int[source.length];

        // the algorithm I'm testing
        for (int i=0; i < encoded.length/2; i++) {
            byte a = encoded[i];
            byte b = encoded[i+1];

            decoded[i] = (short) (a<<8 | b & 0xFF);

        }

        Log.i("XXX", "decoded values: " + decoded.toString());
        
    }
3
  • 1
    what about splitting each int into four parts (i&0xFF, (i>>8)&0xFF, (i>>16)&0xFF and (i>>24)&0xFF)? Commented Jan 21, 2023 at 23:03
  • Note that an int in Java is a 32-bit signed integer. Or are you saying only the low 16-bits are ever used? Commented Jan 22, 2023 at 1:36
  • Yes only 16 ever used. Commented Jan 22, 2023 at 1:46

1 Answer 1

1

Here an exemple...

short[] arrayOfShorts = {6, 1, 2, 5};
byte[] arrayOfBytes = new byte[shortArray.length * 2];
ByteBuffer.wrap(byteArray)
                 .order(ByteOrder.LITTLE_ENDIAN)
                 .asShortBuffer().put(shortArray);
Sign up to request clarification or add additional context in comments.

Comments

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.