Float To 3 unsigned chars

This is a discussion on Float To 3 unsigned chars within the C++ Programming forums, part of the General Programming Boards category; Hi,
I want to be able to convert a float to 3 unsigned chars (as in part of the float ...

Is there a relation between the float value and the values that you want to extract?

OK, I will explain what i am trying to do...

I am trying to implement a z buffer algorithm for a software renderer. Pixels come in with a particular depth between 0.0 and -1.0. I want to be able to store these depths (for later comparisons) in a depth buffer that is really an image consisting of 3 unsigned chars per pixel (RGB). A Pixel In The rendered image has the same pixel location as its depth in the depth buffer, therefore I have 3 * unsigned chars to play with

I'm not entirely sure what you're trying to do here, but if your floats are in the range of [-1, 0], then you could scale that to [0, 2^24-1], and then store than in an integer. Then store 8 of the 24 bits in one of your colors.

If you had a 32bit image, you could probably stuff the entire float in, since an IEEE float is 32bit.

But this whole thing feels like you're pushing a square peg into a round hole.

I'm not entirely sure what you're trying to do here, but if your floats are in the range of [-1, 0], then you could scale that to [0, 2^24-1], and then store than in an integer. Then store 8 of the 24 bits in one of your colors.

If you had a 32bit image, you could probably stuff the entire float in, since an IEEE float is 32bit.

But this whole thing feels like you're pushing a square peg into a round hole.

What Cactus has described here is the way to go. Multiply by -16777215 and cast to int and then you have a number from 0x000000 to 0xFFFFFF. Done.
The bad thing though is that in order to compare depths later, you have to reconstruct the int value, which is additional overhead. If you multiplied by -65535 instead and only used two of the bytes to store it, then you have less work to reconstruct the value later and the result should be approximately as good. You could cast the address of those 3 bytes as a pointer to short, mask off the lowest bit of the pointer, and then access it directly as a nicely-aligned short, for better performance.
For that matter, why don't you just treat it as an array of unsigned shorts directly, completely ignoring the upper one third of the bytes?

I have my own hobby software renderer, so I have a pretty good idea of what is faster most of the time.