在JavaScript中将最低有效数字移出十六进制序列

时间:2018-08-13 00:56:35

标签: javascript integer hex logical-operators

我目前正在尝试写一些东西来调整6位十六进制代码中的蓝色值(它是从高级对象的“颜色”对象中获取的十六进制代码)。

如果尚未设置colours.chosen提供的十六进制代码,或者格式为"#hhhhhh"

//alter hex code value of current set colour
function hexIncrement()
{
  if (colours.chosen == undefined)
  { throw new Error("Trying to alter hex colour code in 'colours' object but this value has not yet been set"); }

  else if (!(/^\s*#\w{6}\s*$/.test(colours.chosen)))
  { throw new Error("'colours.chosen' object attribute does not translate appropriately to a hex value, meaning incorrect");  }

  let pre = colours.chosen.slice(1,5);
  let post = colours.chosen.slice(5, 7);

  post = parseInt(post, 16) + 0x11;
  console.log("added val is", post.toString(16));

  /*if the resultant number exceeds two hex digits 0xFF, then LSR 16 places (computer reads as binary representation) to eliminate extraneous digit*/
  if (post > 0xFF)
  {
    post = 16 >> post;
    console.log("Shifted hex number is: ", post);
  }

  post = post.toString(16);

  while (post.length < 2)
  {
    post += "0";
  }

  //output number in written hex format
  colours.chosen = "#" + pre.toString(16) + post.toString(16);
}

我知道可以通过检测十六进制数字序列的长度并通过字符串切片除去最后一个数字来轻松实现,但是我希望能够以数字方式实现。我的理想结果是将最低有效位简单地删除。

但是,post = 16>>post的结果为0,这怎么可能?

p.s:对我来说,它适用于js.do,但不适用于我的Chrome扩展脚本

1 个答案:

答案 0 :(得分:1)

>>移位二进制数字,因此如果只需要删除最后一位数字,移位post >> 16远远超出您的期望。您想将除以除以16,即post >> 416 == 2 ** 4

let n = parseInt("ffee11", 16)
n = n >> 4
console.log(n.toString(16))

let n2 = 0xaabbcc
n2 = n2 >> 4
console.log(n2.toString(16))

// or divide
let n3 = 0xABFF12
let shifted = Math.floor(n3 / 16).toString(16)
console.log(shifted)