I have a string that contains hex values, something like: "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")
This is something like Ruby's
['1BB3AE3E'].pack('H*')
I have tried creating Buffer.toString, String.fromCharCode, but it didn't work as I expected. 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. Where those C2 are coming from? 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"
For do a good code you should be hexDecode and the protoype and fromCharCode and parseInt, you can do for examples:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.