# convert hex value to integer

I am working on a method defined in a class that controls the lead object. The desired end result is to produce a unique number for each Lead record. I currently have this working, but the out put is a hex value and I need it to be integer. The field to populate is called "Unique_Reference_number__C". An auto-number field is not sufficient, as there are different formats applied contingent on lead field values. Is there a simple way to convert a hex value to an integer? Here is my method:

``````private void GenerateRandomNumber(List<Lead> lList){
System.debug('*lList*********** '+lList.size());
if(l.Unique_Reference_number__c==null || l.Unique_Reference_number__c==''){
System.debug('*1*********** ');
Integer len = 7;
Blob blobKey = crypto.generateAesKey(128);
String key = EncodingUtil.(blobKey);
String pwd = 'ID'+key.substring(0,len);
l.Unique_Reference_number__c= pwd;
System.debug('*1*********** '+pwd);
}
``````

You can convert hex to a value using a few primitive functions:

``````String hex = '0123456789abcdef';
String[] hexValue = sourceHex.split('');
Decimal result = 0;
for(Integer index = 0; index < hexValue.size(); index++) {
result = (result * 16) + hex.indexOf(hexValue[index]);
}
return result;
``````

However, you're likely going to lose precision with a 128-bit key, so you might consider using simply a 64-bit key instead (and put it in a Long instead of Decimal).

• Thanks, this logic worked great! I appreciate your help @sfdcfox! – JoshuaWS Jun 20 '16 at 15:31

hex to int conversion:

``````public static final List<String> hex = '0123456789abcdef'.split('');
public static Integer hexToInt(String str) {
str = str.toLowerCase();
String[] hexValue = str.split('');
Integer retVal = 0;
for(Integer i = 0; i < hexValue.size(); i++) {
retVal = (retVal << 4) + hex.indexOf(hexValue[i]);
}
return retVal;
}
``````

And for anyone interested the int to hex:

``````public static final List<String> hex = '0123456789abcdef'.split('');//same as above
public static string intToHex (Integer num){
integer rem;
String retVal='';
while(num>0)
{
rem = (integer) Math.mod(num, 16);
retVal = hex[rem] + retVal;
num = num / 16;
}
return retVal.leftPad(1, '0');//change 1 to 2 if you are converting from hex to strings afterwards
}
``````