Reputation: 23
My goal is to handle some incoming string that represents a series of hex byte values and output escaped hex values. I also have the freedom to format the string as I please (add spaces, split into chunks etc).
Example(updated):
var input = "FF655050";
var output = "\xFF\x65\x50\x50";
console.log(output); //ÿePP
I've had no success with string manipulation (append, replace) and I'm not really sure of my options here. I really want to avoid a gigantic switch case.
Edit: sorry for not specifying the output correctly. I want the actual escaped character(in escaped form), not the string representation.
Upvotes: 1
Views: 89
Reputation: 30995
Using a loop:
var input = "FF655050";
var output = "";
for (var i = 1; i < input.length; i+=2) {
output += String.fromCharCode(parseInt(input[i-1] + input[i], 16));
}
alert(output)
Or using regular expressions:
var input = "FF655050";
var output = input.replace(/.{0,2}/g, function(x){ return String.fromCharCode(parseInt(x, 16)) });
alert(output)
Upvotes: 1
Reputation: 4505
A simple for loop incremented by two should do the trick.
var input = "FF04CA7B";
var output = "";
for (var i=1; i<input.length; i+=2) {
output += '\\x'+input[i-1]+input[i];
}
Upvotes: 0
Reputation: 82287
Loop through each set of two and prepend "\x" to it
var input = "FF04CA7B";
var i = 0;
var output = "";
while( i < input.length ){
output += "\\x" + input[i];
if(i+1<input.length)output+=input[i+1];
i+=2;
}
alert(output);
Upvotes: 0