在javascript中将十六进制转换为二进制

Har*_*iet 7 javascript

我需要使用javascript将十六进制转换为二进制.

例如:21 23 00 6A D0 0F 69 4C E1 20

应该导致:0010000100100011000000000110101011010000000011110110100101001100

有谁知道我可能用来完成这个的JavaScript库?

哈里特

Seb*_*lor 17

您可以使用以下内容创建将十六进制数转换为二进制数的函数:

function hex2bin(hex){
    return ("00000000" + (parseInt(hex, 16)).toString(2)).substr(-8);
}
Run Code Online (Sandbox Code Playgroud)

对于格式化,你只需用8填充一个字符串0,然后连接你的数字.然后,为了转换,你做的是基本获得一个字符串或数字,使用parseInt带有输入数字值的函数及其基数(此处为十六进制的16),然后使用该函数将其打印到pase 2 toString.最后,您提取最后8个字符以获取格式化的字符串.


2018编辑:

由于这个答案仍在阅读中,我想使用ES8(ECMAScript 2017)String.padStart()方法为函数体提供另一种语法:

function hex2bin(hex){
    return (parseInt(hex, 16).toString(2)).padStart(8, '0');
}
Run Code Online (Sandbox Code Playgroud)

使用padStart将填充字符串,直到其长度与第一个参数匹配,第二个参数是填充字符(默认为空格).

编辑结束


要在像你这样的完整字符串上使用它,请使用简单的forEach:

var result = ""
"21 23 00 6A D0 0F 69 4C E1 20".split(" ").forEach(str => {
  result += hex2bin(str)
})
console.log(result)
Run Code Online (Sandbox Code Playgroud)

输出将是:

00100001001000110000000001101010110100000000111101101001010011001110000100100000


sko*_*iks 9

最简单的实现

const hex2bin = (data) => data.split('').map(i => 
parseInt(i, 16).toString(2).padStart(4, '0')).join('');
Run Code Online (Sandbox Code Playgroud)


Emi*_*sen 6

您可以使用parseInttoString更改数字的基数

function convertNumber(n, fromBase, toBase) {
  if (fromBase === void 0) {
    fromBase = 10;
  }
  if (toBase === void 0) {
    toBase = 10;
  }
  return parseInt(n.toString(), fromBase).toString(toBase);
}
console.log(
  convertNumber("f", 16, 10),
  convertNumber("f", 16, 2),
  convertNumber("1111", 2, 10),
  convertNumber("1111", 2, 16)
);
Run Code Online (Sandbox Code Playgroud)


小智 5

不幸的是,以前的答案似乎不适用于非常大的值(例如,密码学中很常见的 512 位)。这个解决方案可能会慢一点,但它保证处理任何长度的输入。

function hex2bin(hex){
    hex = hex.replace("0x", "").toLowerCase();
    var out = "";
    for(var c of hex) {
        switch(c) {
            case '0': out += "0000"; break;
            case '1': out += "0001"; break;
            case '2': out += "0010"; break;
            case '3': out += "0011"; break;
            case '4': out += "0100"; break;
            case '5': out += "0101"; break;
            case '6': out += "0110"; break;
            case '7': out += "0111"; break;
            case '8': out += "1000"; break;
            case '9': out += "1001"; break;
            case 'a': out += "1010"; break;
            case 'b': out += "1011"; break;
            case 'c': out += "1100"; break;
            case 'd': out += "1101"; break;
            case 'e': out += "1110"; break;
            case 'f': out += "1111"; break;
            default: return "";
        }
    }

    return out;
}
Run Code Online (Sandbox Code Playgroud)