Search code examples
androidrenderscriptandroid-renderscript

How to use half precision in renderscript?


I use the following code to transfer an array of float numbers to a renderscript kernel:

 float[] bufName = new float[3];
 bufName [0] = 255;
 bufName [1] = 255;
 bufName [2] = 0;

 Allocation alloc1 = Allocation.createSized(mRs, Element.F32(mRs), 3);
 alloc1.copy1DRangeFrom(0, 3, mtmd);
 ScriptC_foo foo = new ScriptC_foo(mRs);
 foo.set_gIn(alloc1);

And I have defined gIn in the foo.rs file as follows:

rs_allocation gIn;

I would like to work with 16 bit floating point numbers. I know that I should change the allocation creation to this:

 Allocation alloc1 = Allocation.createSized(mRs, Element.F16(mRs), 3);

However, I cannot find a solution for copying the bufName array to the allocation. Any help is appreciated.


Solution

  • Java does not define half-precision floats, so you'll have to do your own manipulation to get this to work. If you use Float.valueOf(f).shortValue() (where f is the specific flow you'd like to represent as half-precision). This should properly cast down the float to the new bit size. Then create an Allocation of Element.F16 size. You should be able to copy an array of short values down to RenderScript to do the work.