ThePBone
ThePBone

Reputation: 565

Java ByteBuffer in C?

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

Upvotes: 1

Views: 853

Answers (1)

yhyrcanus
yhyrcanus

Reputation: 3813

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,

Upvotes: 2

Related Questions