Scale numbers to be <= 255?

前端 未结 13 2233
生来不讨喜
生来不讨喜 2021-02-05 18:39

I have cells for whom the numeric value can be anything between 0 and Integer.MAX_VALUE. I would like to color code these cells correspondingly.

If the val

13条回答
  •  太阳男子
    2021-02-05 19:10

    For a linear mapping of the range 0-2^32 to 0-255, just take the high-order byte. Here is how that would look using binary & and bit-shifting:

    r = value & 0xff000000 >> 24
    

    Using mod 256 will certainly return a value 0-255, but you wont be able to draw any grouping sense from the results - 1, 257, 513, 1025 will all map to the scaled value 1, even though they are far from each other.

    If you want to be more discriminating among low values, and merge many more large values together, then a log expression will work:

    r = log(value)/log(pow(2,32))*256
    

    EDIT: Yikes, my high school algebra teacher Mrs. Buckenmeyer would faint! log(pow(2,32)) is the same as 32*log(2), and much cheaper to evaluate. And now we can also factor this better, since 256/32 is a nice even 8:

    r = 8 * log(value)/log(2)
    

    log(value)/log(2) is actually log-base-2 of value, which log does for us very neatly:

    r = 8 * log(value,2)
    

    There, Mrs. Buckenmeyer - your efforts weren't entirely wasted!

提交回复
热议问题