在javascript中将十六进制转换为二进制 [英] convert hex to binary in javascript

查看:116
本文介绍了在javascript中将十六进制转换为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to convert hex into binary using javascript.

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

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

应导致:0010000100100011000000000110101011010000000011110110100101001100

should result in: ‭0010000100100011000000000110101011010000000011110110100101001100‬

有人知道我可能会使用的JavaScript库吗?

Does anyone know of a javascript library I might use to accomplish this?

Harriet

推荐答案

您可以创建一个将十六进制数转换为二进制的函数,如下所示:

You can create a function converting a hex number to binary with something like this :

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

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

For formatting you just fill a string with 8 0, and you concatenate your number. Then, for converting, what you do is basicaly getting a string or number, use the parseInt function with the input number value and its base (base 16 for hex here), then you print it to base 2 with the toString function. And finally, you extract the last 8 characters to get your formatted string.

由于此答案仍在阅读中,我想使用ES8(ECMAScript 2017)为该函数的主体提供另一种语法

As this answer is still being read, I wanted to provide another syntax for the function's body, using the ES8 (ECMAScript 2017) String.padStart() method :

function hex2bin(hex){
    return (parseInt(hex, 16).toString(2)).padStart(8, '0');
}

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

Using padStart will fill the string until its lengths matches the first parameter, and the second parameter is the filler character (blank space by default).

编辑结束

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

To use this on a full string like yours, use a simple forEach :

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

输出将是:

00100001001000110000000001101010110100000000111101101001010011001110000100100000

00100001001000110000000001101010110100000000111101101001010011001110000100100000

这篇关于在javascript中将十六进制转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆