JavaScript bin2hex
Converts the binary representation of data to hex
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 | function bin2hex (s){ // Converts the binary representation of data to hex // // version: 1008.1718 // discuss at: http://phpjs.org/functions/bin2hex // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + bugfixed by: Linuxworld // * example 1: bin2hex('Kev'); // * returns 1: '4b6576' // * example 2: bin2hex(String.fromCharCode(0x00)); // * returns 2: '00' var i, f = 0, a = []; s += ''; f = s.length; for (i = 0; i<f; i++) { a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/,"0$1"); } return a.join(''); } |
Examples
» Example 1
Running
1 | bin2hex('Kev'); |
Should return
1 | '4b6576' |
» Example 2
Running
1 | bin2hex(String.fromCharCode(0x00)); |
Should return
1 | '00' |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have bin2hex goodness in JavaScript.
Hi all !
I think there is a bug with some characters in the bin2hex function.
For example, with this char : "Œ" i have the hex : "152"
and it should be "008c" ?
http://www.fileformat.info/info/unicode/char/008c/index.htm
"152" is not an hexadecimal code ?
And it's the same problem with these letters : Š š Ž ž Œ œ Ÿ
Thanks !
Hum, lacks a-f range in the previous snippet,
Hope this time is the good one.
[CODE="Javascript"]
function bin2hex(s){
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + bugfixed by: Linuxworld (v2)
// * example 1: bin2hex('Kev');
// * returns 1: '4b6576'
var v,i, f = 0, a = [];
s += '';
f = s.length;
for(i = 0; i<f; i++){
a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/,"0$1");
}
return a.join('');
}
[/CODE]
Sorry for the previous duplicates, here is the optimized version (ie shorter, with no more str_repeat dependency):
[CODE="Javascript"]
function bin2hex(s){
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + bugfixed by: Linuxworld (v2)
// * example 1: bin2hex('Kev');
// * returns 1: '4b6576'
var v,i, f = 0, a = [];
s += '';
f = s.length;
for(i = 0; i<f; i++){
a[i] = s.charCodeAt(i).toString(16).replace(/^(\d)$/,"0$1");
}
return a.join('');
}
[/CODE]
Now, alert(bin2hex(String.fromCharCode(0x00))) gives 00 which is the expected result.
Hello Kevin,
First, nice job and big thanks for sharing this kind of stuff: JS and PHP worth to be closer thanks to equivalents.
Before fixing your bin2hex function that were not working in my case, I have used one of http://www.paulschou.com/tools/xlate/ that works fine on php side but translated with your js equivalents gave a string with NaN and zeroes..
Your version of bin2hex is buggy and returns a shorter string length due to missing prepending zeroes for low bytes (ie those of value < 0x10). Note that an user has provided a patched version of ord that seems to take this into acccount and with this one, Paul schou's bin2hex equivalent may work on the js side.
Here is the patched and commented version, Enjoy. Linuxworld
/**
*@name bin2hex
*@brief Convert binary data into hexadecimal representation
*@version 2.0
*@requires str_repeat
*@note
* V1.0 - original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
* V1.1 - bugfixed by: Onno Marsman
* V2.0 (18.11.2008) 2 digits for low bytes fix by Linuxworld
*@see http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_bin2hex/
*@internal Similar to recursive ord or encodeuri without %. Be warned encodeuri or encodeuricomponent
* are buggy on both JS/PHP sides. An attempt to reproduce encodeUri was made here http://www.captain.at/howto-php-urlencode-javascript-decodeURIComponent.php but its encoding/decoding
*table is incomplete and thus not as much reliable than bin2hex.
* For all escaping stuff to retrieve hex values: http://xkr.us/articles/javascript/encode-compare/
*@example
* example 1: bin2hex('Kev');
* returns 1: '4b6576'
*@param String s a binary string (ie one given after base64_decode call for sample)
*@return String the hexadecimal representation of the given string.
**/
function bin2hex(s){
var v,i, f = 0, a = [];
s += '';
f = s.length;
for(i = 0; i<f; i++){
v= s.charCodeAt(i).toString(16);
a[i] =str_repeat("0", 2-v.toString().length)+v; //ensures 2 digit code for bytes!
}
return a.join('');
}
Hello Kevin,
First, nice job and big thanks for sharing this kind of stuff: JS and PHP worth to be closer thanks to equivalents.
Before fixing your bin2hex function that were not working in my case, I have used one of http://www.paulschou.com/tools/xlate/ that works fine on php side but translated with your js equivalents gave a string with NaN and zeroes..
Your version of bin2hex is buggy and returns a shorter string length due to missing prepending zeroes for low bytes (ie those of value < 0x10). Note that an user has provided a patched version of ord that seems to take this into acccount and with this one, Paul schou's bin2hex equivalent may work on the js side.
Here is the patched and commented version, Enjoy. Linuxworld
/**
*@name bin2hex
*@brief Convert binary data into hexadecimal representation
*@version 2.0
*@requires str_repeat
*@note
* V1.0 - original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
* V1.1 - bugfixed by: Onno Marsman
* V2.0 (18.11.2008) 2 digits for low bytes fix by Linuxworld
*@see http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_bin2hex/
*@internal Similar to recursive ord or encodeuri without %. Be warned encodeuri or encodeuricomponent
* are buggy on both JS/PHP sides. An attempt to reproduce encodeUri was made here http://www.captain.at/howto-php-urlencode-javascript-decodeURIComponent.php but its encoding/decoding
*table is incomplete and thus not as much reliable than bin2hex.
* For all escaping stuff to retrieve hex values: http://xkr.us/articles/javascript/encode-compare/
*@example
* example 1: bin2hex('Kev');
* returns 1: '4b6576'
*@param String s a binary string (ie one given after base64_decode call for sample)
*@return String the hexadecimal representation of the given string.
**/
function bin2hex(s){
var v,i, f = 0, a = [];
s += '';
f = s.length;
for(i = 0; i<f; i++){
v= s.charCodeAt(i).toString(16);
a[i] =str_repeat("0", 2-v.toString().length)+v; //ensures 2 digit code for bytes!
}
return a.join('');
}
I attempted to use your bin2hex() function, but had a problem with it in my situation (Javascript LM hashes - http://gcopenhaver.com/node/94). Some characters in the string that I was passing to were 0x0f and lower, and this function does not include the first '0' for any of those, causing problems if it's not at the beginning of the string. Here's a function from http://tero.co.uk/des/code.php that will include the '0' if a byte is 0x0f or less. In my use, I removed the '0x' prefix that was set in this function. This is the code as copied from the des.js file. I don't know anything about the licensing of this code.
[CODE="Javascript"]
function stringToHex (s) {
var r = "0x";
var hexes = new Array ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
for (var i=0; i<s.length; i++) {r += hexes [s.charCodeAt(i) >> 4] + hexes [s.charCodeAt(i) & 0xf];}
return r;
}
[/CODE]


Brett Zamir
Apr 13th
However, if you go to their "browser test page", even though you can't see the character in Firefox, if you copy the hidden character there (minus the surrounding spaces and tabs) and use it in the bin2hex function, you'll see that it returns '8c'.
So the behavior of the function is correct. FYI, if you're using Firefox, my extension at https://addons.mozilla.org/en-US/firefox/addon/5235 will let you find the definitions of characters similar to that site and some of the other information it contains, with characters rendered as is, or also available with a transcluded image from the Unicode site itself so you can see how it is supposed to look. And if you are seeking for the real characters, you can use the extension to search by character name, e.g., to search for "oe", you'll turn up U+152 in the chart view.
Also, FYI, many people confuse Windows-1252 with Latin-1 (ISO-8859-1) to such an extent that even browsers do so, and now the HTML5 draft is purposely defining Latin-1 to map to Windows-1252: http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#character-encodings-0 ! To avoid the confusion and get all kinds of other benefits, always use Unicode...