+ Start a Discussion
Tolga SunarTolga Sunar 

Apex - Extra character in string variable problem

Hello,

I have recently stumbled upon a rather interesting problem on my end. I have set up an integration with external system, and it responds me with a Base64 encoded Hex code of a PDF document whenever I make a call with a single input string. I'm supposed to obtain the Hex code after Base64 decoding, then cast the hex code into a blob & save it as an attachment body.

The problem here is: The Hex code itself and its length does not match when I debug. The string is one character less from the size, and the conversion from hex to blob fails because of odd numbered size of input string - it turns out that the size is correct here.

Below is the code:
//Proforma response = Base64 encoded hex string
Blob afterblob = EncodingUtil.base64Decode(proformaResponse);

string HexCode = afterblob.toString();

Debug.Proforma2__c = HexCode;

Debug.Debug1__c = string.valueOf(Hexcode.length());

update Debug;

Note that I use a custom debug object because of sandbox environment's incapability on debugging webservice calls...

When I make the call, HexCode string length is 52312, and Debug1 field value is 52313. Later I submit the HexCode to the EncodingUtil class' ConvertFromHex function, but it fails while saying "input string char count is an odd number"... When I discarded the endmost string of HexCode, it worked, but that's not an approach I want to adopt.

I appreciate any clarification on this issue.
AkankshaAkanksha
Hi Tolga,

In order to convert blob to Hex, please use convertToHex method of Encoding Util Class.

Please refer the below link
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_encodingUtil.htm#apex_System_EncodingUtil_convertToHex


Thanks
Akanksha


 
Tolga SunarTolga Sunar
I'm using that, I just didn't display that line in my post. I am getting odd character count error when I give HexCode variable as input to ConvertToHex, but when I debug HexCode, I clearly see that there is an even number of characters (one less than the length).