I'm looking for a way to uniformly convert JavaScript chars to binary. One problem that I'm facing is that I'm not able to convert strings used in unescape function correctly
document.write("HI"); ==> HI (case 1)
document.write("\x48\x49"); ==> HI (case 2)
document.write(unescape("%48%49")); ==> HI (case 3)
Case 1: Converting "HI" to binary generates:
0100100001001001
Case 2: Converting "\\x48\\x49" to binary generates:
0100100001001001
Case 3: Converting "%48%49" to binary generates:
001001010011010000111000001001010011010000111001
I understand what is happening in case 3. it converts each char to binary without realizing that these chars are in hex representation. I'm wondering if there is a way to make case 3 have the same binary representation as case 1 and case 2 without any pre-processing required?
Ie, is there a function either in JavaScript, Python or any other language that can realize that "%48" is one char represented in hex and is able to convert it to binary?
The decodeURIComponent
is the right function for this. The decode
function is deprecated. Here is an example.
If you put %48%49
in the input and click on the 'Convert' button, it gives you the second case.
var test = document.querySelector("#test"); var btn = document.querySelector("#btn"); var result = document.querySelector("#result"); btn.addEventListener("click", function() { var value = decodeURIComponent(test.value); var resultText = ""; for (i = 0; i < value.length; i++) { resultText += value.charCodeAt(i).toString(2); } result.innerText = resultText; });
<input type="text" id="test"> <button id="btn">Convert</button> <p id="result"></p>
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.