【问题标题】:Convert a hex color into a int32 value with js用js将十六进制颜色转换为int32值
【发布时间】:2020-09-24 20:07:41
【问题描述】:

我有这个值:-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 中再次转换这个颜色。

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

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

【问题讨论】:

  • JavaScript 中没有“int32”这样的东西。您可以将字符串转换为数字。
  • 是的,我知道,但在数据库中,我只从 Visual Basic 获得了“int32”数字。并且知道我需要转换这些颜色。他们得到了 color.toARGB
  • @RyanWilson 那个答案不起作用......他使用了 rgb 颜色。
  • 我不知道a - 它似乎不在您的号码中。 “32768”是对的,减去16^6即可。

标签: javascript hex


【解决方案1】:

我们正在删除“#”,将十六进制解析为十进制,补足 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; }

【讨论】:

  • 谢谢!这正是我想要的
  • 很高兴为您提供帮助!感谢您接受我的回答 - 请您也给它投票吗?
【解决方案2】:

您可以使用parseInt 解析十六进制代码值。只需将基数设置为16。这甚至可以处理三位十六进制代码,例如#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,
    '#$1$1$2$2$3$3').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(",") + ")";
}

【讨论】:

    猜你喜欢
    • 2019-10-29
    • 2020-08-06
    • 2016-05-11
    • 2015-08-25
    • 1970-01-01
    • 2017-10-30
    • 2012-07-25
    • 1970-01-01
    相关资源
    最近更新 更多