Link to home
Start Free TrialLog in
Avatar of Pishky
Pishky

asked on

Testing a value in a range

Hi there gurus.

I am writing a program that converts numerical values into colors

For example

if value is between 0.0 and 0.01 color value is RGB(255,255,0)
                            0.011 and 0.02 color value is RGB(255,255,1)
                                        ...
                                        ...
                                        ...
                            0.091 and 0.1  color value is RGB(255,255,255)
There will be up to 1000 of these ranges
Any idea how to code this.

Regards

Peter
Avatar of jhance
jhance

Many options here:

1) if...else if...else if...else...
2) Table lookup.  If this, write a quick/dirty program to generate your data tables rather then hand-code them.
3) Algorithm.  The above ranges, I assume, are for example only.  But your real situation most likely follows a pattern that can be modeled with an algorithm and implemented in code.
If there are only a few ranges, you can just chain if-else statements.  If there are a lot, then store the RGB values in an array, and convert the ranges to integers (e.g. irange = static_cast<int>(range*100).  This second approach pays the cost of a float->int conversion, but it's much cleaner and easier to maintain, assuming your ranges are all hundredths apart.

Gary
Avatar of Pishky

ASKER

Thank you for the above but I am not sure that this is answering my question. The suggestions above imply a single mapping from one value to another. The problem I have is to map a range of values to a single value.

Regards

Peter
ASKER CERTIFIED SOLUTION
Avatar of GaryFx
GaryFx

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Well

Why not simply use the integer version of the colour.

All the colours are represented by a number in the range [0, 0xFFFFFF]. If your number is in the range [0, 1) just multiply by 2^24. Then if you need to convert it to rgb it's simple.

Value = (long) (YourNumber * 0x1000000);
Red = (Value 0xFF0000) >> 16;
Green = (Value 0xFF00) >> 8;
Blue = (Value 0xFF);

If you want to convert RGB to your number then...

Value = (Red << 16) + (Green << 8) + Blue;
YourNumber = (float) Value / 0x1000000;

No comment has been added lately, so it's time to clean up this question.
I will leave the following recommendation for this question in the Cleanup topic area:

Accept: GaryFx {http:#9622265}

Please leave any comments here within the next four days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Tinchos
EE Cleanup Volunteer