Subscribe to our RSS

Convert ASCII Character to Hex, Decimal and Binary Code

Tags: , , ,

Convert ASCII Character to Hex, Decimal and Binary Code

This JavaScript tutorial explains how to convert ASCII Character to Hex, Decimal and Binary Code using JavaScript.
Recently we were asked for a function code to convert user input to hex code which was intended to be used in a JavaScript remote terminal application. We decided to share this code and also added two more conversion methods to it. The methods are Character to Decimal, Character to Binary, and Decimal to Hex.

The below code object contains the implementation of the various methods. We hope it will be useful to others, and you may use this code in your projects without any limitations. The code can be downloaded it in a separate file here.


var Convert = {
     chars: " !\"#$%&amp;'()*+'-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",
     hex: '0123456789ABCDEF', bin: ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111'],

     decToHex: function(d){
          return (this.hex.charAt((d - d % 16)/16) + this.hex.charAt(d % 16));
     },
     toBin: function(ch){
          var d = this.toDec(ch);
          var l = this.hex.charAt(d % 16);
          var h = this.hex.charAt((d - d % 16)/16);

          var hhex = "ABCDEF";
          var lown = l < 10 ? l : (10 + hhex.indexOf(l));
          var highn = h < 10 ? h : (10 + hhex.indexOf(h));
          return this.bin[highn] + ' ' + this.bin[lown];
     },
     toHex: function(ch){
          return this.decToHex(this.toDec(ch));
     },
     toDec: function(ch){
          var p = this.chars.indexOf(ch);
          return (p <= -1) ? 0 : (p + 32);
     }
};

Here is how to call the above code:

//  Convert Character to Binary (it will return 0100 0001);
Convert.toBin('A');

//  Convert Character to Hex (it will return 41);
Convert.toHex('A');

//  Convert Character to Dec (it will return 65);
Convert.toDec('A');

That’s it ;) Click the Demo button to view it an action.

J

September 8, 2011

I tested your process and found that the ‘&’ in the ‘chars:’ caused all the values to be off. I removed the ‘amp;’ and then it works fine.

eliyas teklu

October 29, 2010

c++programing how is convert character-binery
& binery-character?

eliyas teklu

October 29, 2010

how convert binary to character?
character to binery?

Leave a comment

Your name

October 25, 2014

Spam protection. Enter result of expression you see in the box below.

1 + 4 =