Skip to content

JS 的一些十六进制操作

Published: at 02:43 PMSuggest Changes

我朋友项目中需要用到十六进制的互转,我就顺便记录一下。

十六进制转换为十进制

parseInt('0x1f', 16);

十进制转换为十六进制

(0x1f).toString(16);

十六进制转换为二进制

parseInt('0x1f', 16).toString(2);

二进制转换为十六进制

parseInt('11111', 2).toString(16);

转换为 RGB

function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

alert(rgbToHex(0, 51, 255)); // #0033ff
function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

alert(hexToRgb("#0033ff").g); // "51";
function rgbToHex(r, g, b) {
  return "#" + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1);
}

alert(rgbToHex(0, 51, 255)); // #0033ff
function hexToRgb(hex) {
    var bigint = parseInt(hex, 16);
    var r = (bigint >> 16) & 255;
    var g = (bigint >> 8) & 255;
    var b = bigint & 255;

    return r + "," + g + "," + b;
}

从字符串中提取颜色

function parseColor(input) {
    var div = document.createElement('div'), m;
    div.style.color = input;
    m = getComputedStyle(div).color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i);
    if( m) return [m[1],m[2],m[3]];
    else throw new Error("Colour "+input+" could not be parsed.");
}

其他操作

console.log(Number("0xdc"));

var stringToColour = function(str) {
  var hash = 0;
  for (var i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  var colour = '#';
  for (var i = 0; i < 3; i++) {
    var value = (hash >> (i * 8)) & 0xFF;
    colour += ('00' + value.toString(16)).substr(-2);
  }
  return colour;
}
stringToColour("greenish");
// -> #9bc63b

后记


Previous Post
Mac 使用 exiftool 删除图片元数据
Next Post
CSS 相对居中