Use PHP functions in JavaScript

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: 909.322
    // 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('');
}
external links: original PHP docs | raw js source

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.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Kevin van Zonneveld
25 Nov '08 Permalink

q  @ Linuxworld: Thanks a lot for your thorough contribution!

Gravatar
Linuxworld
22 Nov '08 Permalink

q   Hum, lacks a-f range in the previous snippet,
Hope this time is the good one.

1
2
3
4
56
7
8
9
1011
12
13
14
1516
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&lt;f; i++){
                        a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/,&quot;0$1&quot;);
                }
                return a.join('');        }

Gravatar
Linuxworld
22 Nov '08 Permalink

q   Sorry for the previous duplicates, here is the optimized version (ie shorter, with no more str_repeat dependency):

1
2
3
4
56
7
8
9
1011
12
13
14
1516
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&lt;f; i++){
                        a[i] = s.charCodeAt(i).toString(16).replace(/^(\d)$/,&quot;0$1&quot;);
                }
                return a.join('');        }


Now, alert(bin2hex(String.fromCharCode(0x00))) gives 00 which is the expected result.

Gravatar
Linuxworld
18 Nov '08 Permalink

q   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('');
}

Gravatar
Linuxworld
18 Nov '08 Permalink

q   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('');
}

Gravatar
Greg Copenhaver
9 May '08 Permalink

q   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.

1
2
3
4
56
function stringToHex (s) {
  var r = &quot;0x&quot;;
  var hexes = new Array (&quot;0&quot;,&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;);
  for (var i=0; i&lt;s.length; i++) {r += hexes [s.charCodeAt(i) &gt;&gt; 4] + hexes [s.charCodeAt(i) &amp; 0xf];}
  return r;}


Contribute a New function