[SalesForce] Converting uppercased 18-digit Id to valid Id

I am currently facing an issue where an external system passes back an 18-digit Id that our platform has previously sent to them. However in the process the capitalization of the Id has been removed – read everything has become uppercase. I would imagine somebody has faced this problem before, but apparantly this is not the case.

So in short; is somebody aware of any existing (apex-) function that converts uppercased 18-digit Ids to a valid Salesforce Id?

Please beware; while a lot of answers exist for converting 15 to 18 digits, which is trivial, this is a different problem.

Best Answer

I ported Daniel Ballinger's answer here to Apex:

static String CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345';

static List<Boolean> getBitPattern(String c)
{
    Integer index = CHARS.indexOf(c.toUpperCase());
    List<Boolean> result = new List<Boolean>();
    for (Integer bitNumber = 0; bitNumber < 5; bitNumber++)
        result.add((index & (1 << bitNumber)) != 0);
    return result;
}
static String repairCasing(String input)
{
    if (String.isBlank(input) || input.length() != 18) return input;

    List<Boolean> toUpper = new List<Boolean>();
    toUpper.addAll(getBitPattern(String.valueOf(input.substring(15, 16))));
    toUpper.addAll(getBitPattern(String.valueOf(input.substring(16, 17))));
    toUpper.addAll(getBitPattern(String.valueOf(input.substring(17, 18))));

    String output = '';
    for (Integer i = 0; i < 15; i++)
    {
        String c = String.valueOf(input.substring(i, i+1));
        output += toUpper[i] ? c.toUpperCase() : c.toLowerCase();
    }
    output += input.substring(15, 18).toUpperCase();
    return output;
}

I tested it and it worked:

Id value1 = Id.valueOf('00129000007Kbn7AAC');
Id value2 = Id.valueOf('00129000007KBN7AAC');

system.assertEquals(value1, repairCasing(value2));
Related Topic