Can you decorate a hexadecimal constant so it's interpreted as a float?
Just curious about something. While converting HTML colors (whose individual color components are represented via 2-digit hexadecimal values) to floats开发者_开发问答 between 0.0 and 1.0 so we can use them with OpenGL, I became curious about something. We have to divide the hex values by 255 to give us their OpenGL counterparts, but we can't simply use the hex values as-is because that produces integer division.
Now I know these all work around this issue (of course)...
float r = 0xFD / (float)0xFF; // Works because of the cast to float
float r = 0xFD / 255.0f; // Works because of the explicit float
float d = 0xFF;
float r = 0xFD / d; // Works because 'd' is a float
...but I was wondering if there's any way to just decorate a hex value so it's interpreted as a float (like you do with the 'f' in 1.0f) without having to do casting, calculations or interim variables.
These of course don't work...
float r = 0xFD / 0xFF; // Integer division yields an integer, not float
float r = 0xFD / 0xFFf; // Interprets 'f' as part of the hex value
Again, not trying to find out how to achieve my needed results as my code works just fine. I'm just wondering if I can make the code cleaner via decorating the hex value with something similar to how 'f' works with decimal values instead of using the above-three methods that do work.
This would likely be possible in c++0x using user defined literals but I doubt there is any neat way to do it in c++03.
I'm afraid you have to use preprocessor definition in order to achieve the best look. And you need also casting to perform your computations.
The best solution I can think is
#define COMPONENT8(value) ((float)(value) / 255.0f))
Floating point values cannot be specified as hexadecimal (integer) values.
I don't know of any way to do exactly what you're asking, but if you're looking to use 0xFF repeatedly, why not set it as a constant? That will still preserve typing, i.e:
const float divisor = 0xFF
float r = 0xFD / divisor
I think that'd solve the issue you're looking to solve, even if it's not exactly in the same way.
One way you could do it is by defining your own pattern to define hex floats, 0xff defines hex integers, you could make a macro, like:
#define 0y (float) 0x
Then you just write
float r = 0xAF / 0yFF;
to do your float division.
This solution could though create confusion for others who reads your code, but if the code is mostly for you, than you could do it this way
精彩评论