用js将十六进制颜色转换成int32值

Convert a hex color into a int32 value with js

我有这个值:-16744448; 这个值就是这个颜色:

现在,我需要知道如何更改十六进制的任何值,例如 '#01ff00', '#7fff82', '#c1ffc0', '#16F6F5','#81FFFC','#BFFFFF' 到 int32(是必要的)

function toColor(num) {
    num >>>= 0;
    var b = num & 0xFF,
        g = (num & 0xFF00) >>> 8,
        r = (num & 0xFF0000) >>> 16,
        a = ( (num & 0xFF000000) >>> 24 ) / 255 ;
    return "rgba(" + [r, g, b, a].join(",") + ")";
}

我用了这个公式,但不知道如何应用逆向工程

编辑:

我在数据库中有这个值:-16744448,使用公式我有这个颜色值:'#008000',我需要在 -16744448 中再次转换这个颜色。

当我使用评论中提到的公式时,我得到:32768

这个值来自VB.net,这个函数:Color.FromArgb

您可以用parseInt解析一个十六进制代码值。只需将基数设置为 16。这甚至可以处理 three-digit 十六进制代码,例如 #F00.

不久前我开始写 CSS color value parser,并在下面使用了我的十六进制逻辑。

const colors = [ '#01ff00', '#7fff82', '#c1ffc0', '#16F6F5','#81FFFC','#BFFFFF' ]

console.log(colors.map(color => toColor(hexToInt(color))));

function hexToInt(input) {
  return parseInt(input.replace(/^#([\da-f])([\da-f])([\da-f])$/i,
    '#').substring(1), 16);
}; 

function toColor(num) {
    num >>>= 0;
    const b = num & 0xFF,
          g = (num & 0xFF00) >>> 8,
          r = (num & 0xFF0000) >>> 16,
          a = ( (num & 0xFF000000) >>> 24 ) / 255 ;
    return "rgba(" + [r, g, b, a].join(",") + ")";
}

我们正在删除“#”,从十六进制解析为十进制,补足 16^6。
返回:
反补码,以十六进制字符串填充前导零,修剪到最后 6,在开头添加“#”。

var values=["#008000",'#01ff00', '#7fff82', '#c1ffc0', '#16F6F5','#81FFFC','#BFFFFF'];

values.forEach(v=>{
  var r=parseInt(v.slice(-6),16)-Math.pow(16,6);
  var rr="#"+("0".repeat(6)+(Math.pow(16,6)+r).toString(16)).slice(-6);
  console.log(v,r,rr);
});
.as-console-wrapper { max-height: 100% !important; top: 0; }