Unorm and SNORM to float, hardware edition
fgiesen.wordpress.com
fgiesen.wordpress.com
union {
int bits;
float f;
} pun = {x}, scale = {0x47000000};
pun.bits |= scale.bits;
pun.f -= scale.f;
pun.f *= (256/255.0f);
This basically amounts to a software implementation of int->float conversion instructions; sadly I have never found a spot where it's actually worth doing when you have those int->float instructions available already, even with the FMA as a single instruction.It's also worth considering whether your application can handle approximate conversion. If you have a [0,255] unorm in x, x + (x>>7) or equivalently x + (x>0x7f) will round it to a [0,256] fixed-point value. Crucially, this rounding does handle 0x00 and 0xff inputs correctly. Once in fixed-point with a nice power-of-two divisor, you can play all sorts of tricks, either again making use of the bit representation of floats, using ARM fixed-point instructions, etc. If you've ever looked longingly at the pmulhrsw family of instructions, this is a ripe area to explore.
For funsies I asked chatgpt 4o to try:
uint16_t product = x * 257; // Multiply by 257
return product >> 16; // Shift right by 16 bits
A valiant effort, and confidently presented. When pressed and given the methods from the article to compare with it admitted it may suffer from precision issues, but was ultimately the best of the three.The Achilles heel of this approach (and of blindly trusting LLM code in general) is left as an exercise.
float uint8_div_255(uint8_t x) {
uint32_t y = x * 0x010101u; // x * 65793
return ((float)y) * (1.0f / 16777215.0f);
}A barrel of oil is currently $70, so if you’ve spent more than that on your chat, you’ve gone through an “energy slave for a year” in a matter of minutes! (A barrel of oil contains the same energy as the work done by a human labourer over a year.)
Note: You might argue that most of the cost is due to the rental on the chips and not the electrical bill. Sure, but a silicon chip has a minuscule material cost and is mostly expensive because of the energy-intensive processes required to make it.