如何实现 hex2bin()?

发布于 2024-12-09 01:55:22 字数 189 浏览 0 评论 0原文

我需要在 Javascript 和 PHP 之间进行通信(我使用 jQuery 进行 AJAX),但 PHP 脚本的输出可能包含二进制数据。这就是为什么我在 PHP 端使用 bin2hex()json_encode()

如何使用 JavaScript 将十六进制字符串转换为二进制字符串?

I need to communicate between Javascript and PHP (I use jQuery for AJAX), but the output of the PHP script may contain binary data. That's why I use bin2hex() and json_encode() on PHP side.

How do I convert the hexadecimal string in binary string, with JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

一杆小烟枪 2024-12-16 01:55:22

回答您的问题:

function Hex2Bin(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(2)}

以下是您可能会发现对处理二进制数据有用的一些其他函数:

//Useful Functions
function checkBin(n){return/^[01]{1,64}$/.test(n)}
function checkDec(n){return/^[0-9]{1,64}$/.test(n)}
function checkHex(n){return/^[0-9A-Fa-f]{1,64}$/.test(n)}
function pad(s,z){s=""+s;return s.length<z?pad("0"+s,z):s}
function unpad(s){s=""+s;return s.replace(/^0+/,'')}

//Decimal operations
function Dec2Bin(n){if(!checkDec(n)||n<0)return 0;return n.toString(2)}
function Dec2Hex(n){if(!checkDec(n)||n<0)return 0;return n.toString(16)}

//Binary Operations
function Bin2Dec(n){if(!checkBin(n))return 0;return parseInt(n,2).toString(10)}
function Bin2Hex(n){if(!checkBin(n))return 0;return parseInt(n,2).toString(16)}

//Hexadecimal Operations
function Hex2Bin(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(2)}
function Hex2Dec(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(10)}

To answer your question:

function Hex2Bin(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(2)}

Here are some further functions you may find useful for working with binary data:

//Useful Functions
function checkBin(n){return/^[01]{1,64}$/.test(n)}
function checkDec(n){return/^[0-9]{1,64}$/.test(n)}
function checkHex(n){return/^[0-9A-Fa-f]{1,64}$/.test(n)}
function pad(s,z){s=""+s;return s.length<z?pad("0"+s,z):s}
function unpad(s){s=""+s;return s.replace(/^0+/,'')}

//Decimal operations
function Dec2Bin(n){if(!checkDec(n)||n<0)return 0;return n.toString(2)}
function Dec2Hex(n){if(!checkDec(n)||n<0)return 0;return n.toString(16)}

//Binary Operations
function Bin2Dec(n){if(!checkBin(n))return 0;return parseInt(n,2).toString(10)}
function Bin2Hex(n){if(!checkBin(n))return 0;return parseInt(n,2).toString(16)}

//Hexadecimal Operations
function Hex2Bin(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(2)}
function Hex2Dec(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(10)}
迷鸟归林 2024-12-16 01:55:22

JavaScript 不支持二进制数据。不过,您可以使用常规字符串来模拟这一点。

var hex = "375771", // ASCII HEX: 37="7", 57="W", 71="q"
    bytes = [],
    str;

for(var i=0; i< hex.length-1; i+=2){
    bytes.push(parseInt(hex.substr(i, 2), 16));
}

str = String.fromCharCode.apply(String, bytes);

alert(str); // 7Wq

JavaScript doesn't have support for binary data. Nevertheless you can emulate this with regular strings.

var hex = "375771", // ASCII HEX: 37="7", 57="W", 71="q"
    bytes = [],
    str;

for(var i=0; i< hex.length-1; i+=2){
    bytes.push(parseInt(hex.substr(i, 2), 16));
}

str = String.fromCharCode.apply(String, bytes);

alert(str); // 7Wq
单挑你×的.吻 2024-12-16 01:55:22
function hex2bin(hex)
{
    var bytes = [], str;

    for(var i=0; i< hex.length-1; i+=2)
        bytes.push(parseInt(hex.substr(i, 2), 16));

    return String.fromCharCode.apply(String, bytes);    
}

感谢安德里斯


有关此主题(dex2bin、bin2dec)的其他有用信息可以在此处< /a>.
据此,这是一个 bin2hex 解决方案:

parseInt(1100,2).toString(16); //--> c
function hex2bin(hex)
{
    var bytes = [], str;

    for(var i=0; i< hex.length-1; i+=2)
        bytes.push(parseInt(hex.substr(i, 2), 16));

    return String.fromCharCode.apply(String, bytes);    
}

thanks to Andris!


Other useful information about this topic (dex2bin,bin2dec) can be found here.
According to that, here is a bin2hex solution:

parseInt(1100,2).toString(16); //--> c
再浓的妆也掩不了殇 2024-12-16 01:55:22

虽然不是实际问题的答案,但在这种情况下了解如何反转该过程可能很有用:

function bin2hex (bin)
{

  var i = 0, l = bin.length, chr, hex = ''

  for (i; i < l; ++i)
  {

    chr = bin.charCodeAt(i).toString(16)

    hex += chr.length < 2 ? '0' + chr : chr

  }

  return hex

}

例如,在 b637eb9146e84cb79f6d981ac9463de1 上使用 hex2bin 返回 ¶7ëFèL·mÉF=á,然后将其传递给 bin2hex 返回b637eb9146e84cb79f6d981ac9463de1

将这些函数原型化为 String 对象也可能很有用:

String.prototype.hex2bin = function ()
{

  var i = 0, l = this.length - 1, bytes = []

  for (i; i < l; i += 2)
  {
    bytes.push(parseInt(this.substr(i, 2), 16))
  }

  return String.fromCharCode.apply(String, bytes)   

}

String.prototype.bin2hex = function ()
{

  var i = 0, l = this.length, chr, hex = ''

  for (i; i < l; ++i)
  {

    chr = this.charCodeAt(i).toString(16)

    hex += chr.length < 2 ? '0' + chr : chr

  }

  return hex

}

alert('b637eb9146e84cb79f6d981ac9463de1'.hex2bin().bin2hex())

Although not an answer to the actual question, it is perhaps useful in this case to also know how to reverse the process:

function bin2hex (bin)
{

  var i = 0, l = bin.length, chr, hex = ''

  for (i; i < l; ++i)
  {

    chr = bin.charCodeAt(i).toString(16)

    hex += chr.length < 2 ? '0' + chr : chr

  }

  return hex

}

As an example, using hex2bin on b637eb9146e84cb79f6d981ac9463de1 returns ¶7ëFèL·mÉF=á, and then passing this to bin2hex returns b637eb9146e84cb79f6d981ac9463de1.

It might also be useful to prototype these functions to the String object:

String.prototype.hex2bin = function ()
{

  var i = 0, l = this.length - 1, bytes = []

  for (i; i < l; i += 2)
  {
    bytes.push(parseInt(this.substr(i, 2), 16))
  }

  return String.fromCharCode.apply(String, bytes)   

}

String.prototype.bin2hex = function ()
{

  var i = 0, l = this.length, chr, hex = ''

  for (i; i < l; ++i)
  {

    chr = this.charCodeAt(i).toString(16)

    hex += chr.length < 2 ? '0' + chr : chr

  }

  return hex

}

alert('b637eb9146e84cb79f6d981ac9463de1'.hex2bin().bin2hex())
川水往事 2024-12-16 01:55:22

所有建议的解决方案都使用 String.fromCharCode,为什么不简单地使用 unescape

String.prototype.hex2bin = function()
{ 
   var i = 0, len = this.length, result = "";

   //Converting the hex string into an escaped string, so if the hex string is "a2b320", it will become "%a2%b3%20"
   for(; i < len; i+=2)
      result += '%' + this.substr(i, 2);      

   return unescape(result);
}

进而:

alert( "68656c6c6f".hex2bin() ); //shows "hello"

All proposed solutions use String.fromCharCode, why not simply using unescape?

String.prototype.hex2bin = function()
{ 
   var i = 0, len = this.length, result = "";

   //Converting the hex string into an escaped string, so if the hex string is "a2b320", it will become "%a2%b3%20"
   for(; i < len; i+=2)
      result += '%' + this.substr(i, 2);      

   return unescape(result);
}

and then:

alert( "68656c6c6f".hex2bin() ); //shows "hello"
嘦怹 2024-12-16 01:55:22

参考node.js(不在浏览器中)。

基本上,它都是过度设计的,并且效果不佳。

响应不一致,尽管从文本角度来看,它们在位方面是相同的,但一切都到处都是:

curl http://phpimpl.domain.com/testhex.php | xxd

00000000: de56 a735 4739 c01d f2dc e14b ba30 8af0  .Q.%G9.....;.0..

curl http://nodejs.domain.com/ | xxd

00000000: c39e 56c2 a725 4739 c380 c3ad c3b1 c39c  ..Q..%G9........
00000010: c3a1 37c2 6b30 c28f c3b0                 ..;..0....

在节点中实现此操作的正确方法是:

function hex2bin(hex){
   return new Buffer(hex,"hex");
}


curl http://nodejs.domain.com/ | xxd

00000000: de56 a735 4739 c01d f2dc e14b ba30 8af0  .Q.%G9.....;.0..

希望这会有所帮助。

With reference to node.js ( not in browser ).

Basically it's all over-engineered and does not work well.

responses are out of alignment and though text-wise they are the same bit wise everything is all over the place :

curl http://phpimpl.domain.com/testhex.php | xxd

00000000: de56 a735 4739 c01d f2dc e14b ba30 8af0  .Q.%G9.....;.0..

curl http://nodejs.domain.com/ | xxd

00000000: c39e 56c2 a725 4739 c380 c3ad c3b1 c39c  ..Q..%G9........
00000010: c3a1 37c2 6b30 c28f c3b0                 ..;..0....

The proper way to implement this in node is :

function hex2bin(hex){
   return new Buffer(hex,"hex");
}


curl http://nodejs.domain.com/ | xxd

00000000: de56 a735 4739 c01d f2dc e14b ba30 8af0  .Q.%G9.....;.0..

Hope this helps.

久隐师 2024-12-16 01:55:22

这是 JS 中 hex2bin 的实现,它接受一个字符串并返回 Uint8Array,在浏览器和 Nodejs 中都可以工作,

function hex2bin(hex) {
  var length = hex.length / 2;
  var result = new Uint8Array(length);
  for (var i = 0; i < length; ++i) {
    result[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
  }
  return result;
}

以及它的逆,

function bin2hex(bin) {
  return Array.from(bin).map(function (x) {
    return x.toString(16).padStart(2, '0');
  }).join('');
}

Here is an implementation of hex2bin in JS that takes a string and returns Uint8Array, works both in browsers and nodejs,

function hex2bin(hex) {
  var length = hex.length / 2;
  var result = new Uint8Array(length);
  for (var i = 0; i < length; ++i) {
    result[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
  }
  return result;
}

And its inverse,

function bin2hex(bin) {
  return Array.from(bin).map(function (x) {
    return x.toString(16).padStart(2, '0');
  }).join('');
}
太阳男子 2024-12-16 01:55:22
String.prototype.hex2bin = function () {
    if (this.length % 2 !== 0) return false;

    let bytes = []
    for (let i = 0; i < this.length - 1; i += 2) {
        let charCode = parseInt(this.substring(i, i + 2), 16)
        bytes.push(charCode)
    }

    return String.fromCharCode.apply(String, bytes)
        .replace(/\x00+$/g, '') // not necessary
        .trim()
}
    
console.log('78534F4C41527800000000000000000000000000'.hex2bin()) // xSOLARx (length: 7)
console.log('4D554C5449504153530000000000000000000000'.hex2bin()) // MULTIPASS (length: 9)
console.log('4C5A415200000000000000000000000000000000'.hex2bin()) // LZAR (length: 4)

String.prototype.hex2bin = function () {
    if (this.length % 2 !== 0) return false;

    let bytes = []
    for (let i = 0; i < this.length - 1; i += 2) {
        let charCode = parseInt(this.substring(i, i + 2), 16)
        bytes.push(charCode)
    }

    return String.fromCharCode.apply(String, bytes)
        .replace(/\x00+$/g, '') // not necessary
        .trim()
}
    
console.log('78534F4C41527800000000000000000000000000'.hex2bin()) // xSOLARx (length: 7)
console.log('4D554C5449504153530000000000000000000000'.hex2bin()) // MULTIPASS (length: 9)
console.log('4C5A415200000000000000000000000000000000'.hex2bin()) // LZAR (length: 4)

清风不识月 2024-12-16 01:55:22

如果有人需要另一个方向(二进制到十六进制),这里是:

function bin2hex(bin) {
    return new Buffer(bin).toString("hex");
}

If someone needs the other direction (bin to hex), here is it:

function bin2hex(bin) {
    return new Buffer(bin).toString("hex");
}
冰雪之触 2024-12-16 01:55:22

JavaScript 实际上包含对二进制数据的支持。请参阅 Uint8Array

只需从数组中读取每个字节并将其转换为十六进制即可。

JavaScript does actually contain support for binary data. See Uint8Array.

Just read each byte from the array and convert it into hexadecimal.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文