1

I need to translate a Java method, which uses the ByteBuffer object to C. How can I accurately replicate the code below using Java's ByteBuffer? And what data types should I use to embed floats in a byte array (in C)?

The code I spoke about:

public void example(float[] floatData) {
    //Initialize byte array "byteData"
    byte[] byteData = new byte[floatData.length * 4];
    ByteBuffer byteDataBuffer = ByteBuffer.wrap(byteData);
    byteDataBuffer.order(ByteOrder.nativeOrder());

    //Fill byte array with data from floatData
    for (int i = 0; i < floatData.length; i++)
    byteDataBuffer.putFloat(floatData[i]);

    //Concat length of array (as byte array) to "byteData"
    byte[] vL = intToByteArray(floatData.length / 2);
    byte[] v = concatArrays(vL, byteData);

    //Fill the remaining array with empty bytes
    if (v.length < 1024) {
        int zeroPad = 1024 - v.length;
        byte[] zeroArray = new byte[zeroPad];
        v = concatArrays(v, zeroArray);
        zeroArray = null;
    }

    //[Do something with v[] here...]
}

FloatData[] can look something like this: 1.00052387686001,-1.9974419759404,0.996936345285375

2
  • Use calloc to allocate the space (1024). Set the length as the first sizeof(int) bytes, then use memcpy to copy the float array over to the rest of the allocated memory (sizeof(float)*length). I don't see a p[] anywhere? Commented Jun 7, 2019 at 19:12
  • Yes i removed that last minute, because it wasn't relevant Commented Jun 7, 2019 at 19:16

1 Answer 1

2

Use calloc to allocate the space (1024). Set the length as the first sizeof(int) bytes, then use memcpy to copy the float array over to the rest of the allocated memory (sizeof(float)*length).

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

void example(float * fAry, int length){
    int i;
    unsigned char* bAry = calloc(1024,1);

    memcpy(bAry,&length,sizeof(int));    
    memcpy(bAry + sizeof(int), fAry, length*(sizeof(float)));

    for (i=0; i<20; i++){
        printf("%u,",bAry[i]);
    }

    free(bAry);
}


int main()
{
    float ary[3] ={1.1,1.2,1.3};

    example(ary,3);

    return 0;
}

output:

3,0,0,0,205,204,140,63,154,153,153,63,102,102,166,63,0,0,0,0,

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.