string to hex code example

Example 1: to hex javascript

var rgbToHex = function (rgb) { 
  var hex = Number(rgb).toString(16);
  if (hex.length < 2) {
       hex = "0" + hex;
  }
  return hex;
};

Example 2: javascript hex to string

function hex_to_ascii(str1)
 {
	var hex  = str1.toString();
	var str = '';
	for (var n = 0; n < hex.length; n += 2) {
		str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
	}
	return str;
 }

Example 3: String to hexadecimal in java

// String to hexadecimal in java
import java.util.Scanner;
public class StringToHexJava
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a string: ");
      String strInput = sc.next();
      StringBuffer sb = new StringBuffer();
      char[] chArray = strInput.toCharArray();
      for(int a = 0; a < chArray.length; a++)
      {
         String strHexadecimal = Integer.toHexString(chArray[a]);
         sb.append(strHexadecimal);
      }
      String strOutput = sb.toString();
      System.out.println(strOutput);
      sc.close();
   }
}

Tags:

Java Example