RGB to hex and hex to RGB

前端 未结 30 2832
遥遥无期
遥遥无期 2020-11-21 06:56

How to convert colors in RGB format to hex format and vice versa?

For example, convert \'#0080C0\' to (0, 128, 192).

30条回答
  •  失恋的感觉
    2020-11-21 07:19

    I'm assuming you mean HTML-style hexadecimal notation, i.e. #rrggbb. Your code is almost correct, except you've got the order reversed. It should be:

    var decColor = red * 65536 + green * 256 + blue;
    

    Also, using bit-shifts might make it a bit easier to read:

    var decColor = (red << 16) + (green << 8) + blue;
    

提交回复
热议问题