Reputation: 435
I need to pack an int into a float and then convert it back into an int again. I dont have access to the floats memory so I cant read specific bits of the float. Im stuck in GLSL 130.
My attempt seems to work for most numbers but I am concerned that for some numbers I will get a rounding error because of the way floats are represented. Are rounding errors something that could happen? What can I do to prevent them? Right now Im cramming four 7 bit ints into one float. In the example code Im just packing one int, but in my real code I pack 4 of em. I could reduce that to two ints per float, would that help?
packing code in cpp
for (int i = 0; i < 7; i++) {
packedFloat += static_cast<float>((intToPack >> i) & 1) * (1 << i);
}
unpacking code in GLSL
int unpackedInt = 0;
for (int i = 0; i < 7; i++) {
float divisor = pow(2.0, i);
float remainder = mod(packedFloat, divisor * 2.0);
int bit_i = int(floor(remainder / divisor));
unpackedInt |= (bit_i << i);
}
Upvotes: 0
Views: 47