简体   繁体   English

不带编码的十六进制字符串

[英]String from hex without encoding

I have a string that contains hex values, something like: "1BB3AE3E". 我有一个包含十六进制值的字符串,如:“1BB3AE3E”。

Now I would like to convert this to a string (expected result "≥Æ>") of exactly that byte representation (so written to a file, and opened with hex viewer would show "1BB3AE3E") 现在我想把它转换成一个字符串(预期结果“≥Æ>”)的字节表示(因此写入文件,并用十六进制查看器打开将显示“1BB3AE3E”)

This is something like Ruby's 这就像Ruby一样

['1BB3AE3E'].pack('H*')

I have tried creating Buffer.toString, String.fromCharCode, but it didn't work as I expected. 我尝试过创建Buffer.toString,String.fromCharCode,但它没有按照我的预期工作。 The closes I got to the result was with 我得到的结果是关闭的

var input = "1BB3AE3E"
var buffer = new Buffer(input, "hex")
var result = buffer.toString("binary")

and it resulted with a file containing "³®>" for which hex is: 1B C2 B3 C2 AE 3E. 它产生一个包含“³>”的文件,其中十六进制为:1B C2 B3 C2 AE 3E。 Where those C2 are coming from? 那些C2来自哪里? How can I make it work? 我怎样才能使它工作?

I've also tried 我也试过了

var hexes = this.match(/.{1,2}/g) || [];
var back = "";
for(j = 0; j< hexes.length; j++) {
    back += String.fromCharCode(parseInt(hexes[j], 16));
}

but to no vain. 但没有白费。 The effect is as above. 效果如上。

//var result= parseInt(buffer, 16).toString(2)
  var result= parseInt(input, 16).toString(2)

Output:"11011101100111010111000111110"

also see: https://gist.github.com/faisalman/4213592 另见: https//gist.github.com/faisalman/4213592

For do a good code you should be hexDecode and the protoype and fromCharCode and parseInt, you can do for examples: 为了做一个好的代码你应该是hexDecode和原型以及fromCharCode和parseInt,你可以做的例子:

String.prototype.hexDecode = function(){
    var j;
    var hexes = this.match(/.{1,4}/g) || [];
    var back = "";
    for(j = 0; j<hexes.length; j++) {
        back += String.fromCharCode(parseInt(hexes[j], 16));
    }

    return back;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM