Passing Unity Mathematics half2 into StructuredBuffer

I’m trying to pass half2 from a ComputeBuffer into a StructuredBuffer but the value i get in there are all messed up.
I know half2 has x and y that are ushort (16 bit unsigned integers) and half2 on the shader side is 16 bit signed float but can’t get it to work properly.
Also tried to pass half2 in to StructuredBuffer and then performing a conversion from uint → float like this:

float uintToFloat(uint x)
{
 const uint shifted_exp = (0x7c00 << 13);
 uint uf = (x & 0x7fff) << 13;
 uint e = uf & shifted_exp;
 uf += (127 - 15) << 23;
 uf += lerp(0, (128u - 16u) << 23, e == shifted_exp);
 uf = lerp(uf, asuint(asfloat(uf + (1 << 23)) - 6.10351563e-05f), e == 0);
 uf |= (x & 0x8000) << 16;
 return asfloat(uf);
}

Can anyone help me with the conversion required in here?

Thanks!

A compute buffer of half2 is a stride of 32 bits as each half is 16 bits. A structured buffer of uint2 is a stride of 64 bits as each uint is 32 bits. What you want is to use a structured buffer with a single uint and convert the top 16 bits and bottom 16 bits each into separate floats.

float2(uintToFloat((x & 0xFFFF0000) >> 16), uintAsFloat(x & 0x0000FFFF))

Or use a compute buffer that uses float values instead and skip the conversion headache.

3 Likes

Thank you.
That is exactly what i want.
I had to reverse the order for it to work.

float2(uintToFloat(x & 0x0000FFFF), uintToFloat((x & 0xFFFF0000) >> 16))

The reason i use half2 is because setting a large array of half2 is way faster than setting the same array of float2.

Again thank you :slight_smile: