5

I have string in controller which contains some Hex character. I want to convert that character in string so that I can save it. Can anyone help?

Thanks in advance.

2
  • 1
    Are you talking about a Hex string or a Hex character? Have you looked at the EncodingUtil Class in the Apex documentation? If that doesn't do what you want, then I'd think your next recourse is going to be to use some kind of regex based solution.
    – crmprogdev
    Apr 1, 2013 at 15:03
  • 4
    Please share an example of your string along with its encoding? Apr 1, 2013 at 20:28

4 Answers 4

9

To convert from a String to a Hex value, use the EncodingUtil class.

To convert from Hex to a String, check out this thread in the Community Forum: http://boards.developerforce.com/t5/Apex-Code-Development/Method-to-convert-Hex-to-String-or-blob/td-p/187747. Here's the code posted there (see below):

// convert Hex to UTF-8 (now works with multibyte locales!)
// http://boards.developerforce.com/t5/Apex-Code-Development/Method-to-convert-Hex-to-String-or-blob/td...
private static Map < String, Integer > hexMap = new Map < String, Integer > ();
static{
  hexMap.put('0', 0);
  hexMap.put('1', 1);
  hexMap.put('2', 2);
  hexMap.put('3', 3);
  hexMap.put('4', 4);
  hexMap.put('5', 5);
  hexMap.put('6', 6);
  hexMap.put('7', 7);
  hexMap.put('8', 8);
  hexMap.put('9', 9);
  hexMap.put('A', 10);
  hexMap.put('B', 11);
  hexMap.put('C', 12);
  hexMap.put('D', 13);
  hexMap.put('E', 14);
  hexMap.put('F', 15);
  hexMap.put('a', 10);
  hexMap.put('b', 11);
  hexMap.put('c', 12);
  hexMap.put('d', 13);
  hexMap.put('e', 14);
  hexMap.put('f', 15);
}

public class UTFException extends Exception{
}

public static List < Integer > hexToInt(String hex) {
  List < Integer > retVal = new List < Integer > ();
  Integer i = 0;
  while(i < hex.length()) {

    // http://en.wikipedia.org/wiki/UTF-8
    integer numberOfBytes = 1;
    integer byte1 = 0,
    byte2 = 0,
    byte3 = 0,
    byte4 = 0;
    integer utfCode = 0;
    byte1 = (hexMap.get(hex.substring(i, i + 1)) * 16) + (hexMap.get(hex.substring(i + 1, i + 2)));

    //invalid sequences for byte1
    if(byte1 >= 128 && byte1 <= 191) {
      throw new UTFException('UTF-8:Continuation byte as first byte');
    }
    if(byte1 >= 192 && byte1 <= 193) {
      throw new UTFException('UTF-8:Invalid 2-byte sequence');
    }
    if(byte1 >= 245) {
      throw new UTFException('UTF-8:Invalid 4,5 or 6-byte sequence');
    }

    if(byte1 >= 192) {
      numberOfBytes = 2;
      byte2 = (hexMap.get(hex.substring(i + 2, i + 2 + 1)) * 16) + (hexMap.get(hex.substring(i + 2 + 1, i + 2 + 2)));
    }
    if(byte1 >= 224) {
      numberOfBytes = 3;
      byte3 = (hexMap.get(hex.substring(i + 4, i + 4 + 1)) * 16) + (hexMap.get(hex.substring(i + 4 + 1, i + 4 + 2)));
    }
    if(byte1 >= 240) {
      numberOfBytes = 4;
      byte4 = (hexMap.get(hex.substring(i + 6, i + 6 + 1)) * 16) + (hexMap.get(hex.substring(i + 6 + 1, i + 6 + 2)));
    }
    if(numberOfBytes == 1) {
      utfCode = byte1;
    } else if(numberOfBytes == 2) {
      utfCode = Math.mod(byte1, 32) * 64 + Math.mod(byte2, 64);
    } else if(numberOfBytes == 3) {
      utfCode = Math.mod(byte1, 16) * 64 * 64 + Math.mod(byte2, 64) * 64 + Math.mod(byte3, 64);
    } else if(numberOfBytes == 4) {
      utfCode = Math.mod(byte1, 8) * 64 * 64 * 64 + Math.mod(byte2, 64) * 64 * 64 + Math.mod(byte3, 64) * 64 + Math.mod(byte4, 64);
    }

    retVal.add(utfCode);
    i += 2 * numberOfBytes;
  }
  return retVal;
}

public static Blob HexToUTF(string hex) {
  string text = String.fromCharArray(hexToInt(hex));
  return Blob.valueOf(text);
}
4

It can be done with fromCharArray method.

(1) Do a math to transfer Hex to Dec
(2) Convert Dec to Ascii

Here is an example code:

List<Integer> charArray = new List<Integer>();
charArray.add(60);
System.debug(String.fromCharArray(charArray));

Ref:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_System_String_fromCharArray.htm

0

I found out that EncodingUtil.urlEncode('myString', 'UTF-8') method seems to have the same effect.

Please check it up.

string ch = 'é';
string result = EncodingUtil.urlEncode(ch, 'UTF-8');
system.debug('*** result: '+result);

This would print the following result: %C3%A9

0

I was facing same requirement so I built my own code.

  1. Do a math to transfer Hex to Dec

  2. Convert Dec to Ascii

public class Hexa_2_string {
    /*
     * Developer Name : Teekam singh
     * Functionality: Conversion of hexadecimal to string 
     * version : 1.0.1 
     */
        
    public static void hexatostring(){
        //take input in hexadecimal number
        String hex = '576f726c6427732073696d706c657374206f6e6c696e65207465787420746f2068657861646563696d616c';
        String output = '';
        for(integer i=0; i<hex.length(); i+=2){
            String subtype;
            if(i+2 > hex.length()){
                subtype = hex.substring(i, i+1);                
            }else{
                subtype = hex.substring(i, i+2);
            }
            
            Integer result = convert2decimal(subtype);
            //System.debug('inner value is '+result);
            string str = String.fromCharArray(new Integer[]{result});
            //System.debug('str is '+str);
            output +=str;
            //System.debug('temp '+temp);
        }
        
        System.debug('final is '+ output);        
    }
    /*
     * This function will convert hexadecimal to decimal
     */
    public static integer convert2decimal(String hex){
        
        String rev = hex.reverse();
        String[] hexValue = rev.split('');
        integer base = 0;   
        integer result = 0;
        Map<String,Integer> mymap = convertCharintonum();
        for(Integer index = 0; index < hexValue.size(); index++) {
            Object temp;
            if(mymap.containsKey(hexValue[index])){
                temp = mymap.get(hexValue[index]);
            }else{
                temp = hexValue[index];
            }
            result += Integer.valueOf(temp) * Integer.valueOf(Math.pow(16, base));
            base += 1;   
            
        }
        System.debug(result);
        return result;
        
    }
    
    public static Map<String,integer> convertCharintonum(){
        Map<String,Integer> mymap = new Map<String,Integer>();
        mymap.put('A',10);        
        mymap.put('B',11);
        mymap.put('C',12);
        mymap.put('D',13);
        mymap.put('E',14);
        mymap.put('F',15);
        mymap.put('a',10);
        mymap.put('b',11);
        mymap.put('c',12);
        mymap.put('d',13);
        mymap.put('e',14);
        mymap.put('f',15);
        return mymap;
        
    }
}

output :- World's simplest online text to hexadecimal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.