Convert a RGB colour value to Decimal

前端 未结 6 1312
梦谈多话
梦谈多话 2021-02-04 13:09

How do I convert a RGB colour value to just plain decimal?

So I have: RGB(255,255,255) is white
Its decimal equivalent is: 16777215

I have tried thinking it

6条回答
  •  梦如初夏
    2021-02-04 13:30

    var dec = (b & 0xff) << 16 + (g & 0xff) << 8 + (r & 0xff);
    

    (I think that's the correct order for the r,g,b values)

    Update

    I just checked for browser applications and I got the order wrong, so the correct formula for browsers (read HTML+CSS+javascript) is:

    var dec = r << 16 + g << 16 + b;
    

    Assuming r,g,b values <= 255

    Other API's may expect a different order for the r,g,b values. I seem to remember at least one that has the order reversed (per my original answer), but I think which one it is at the moment.

提交回复
热议问题