Pregunta

The Hexa-Tri-Decimal number is 0-9 and A-Z. I know I can covert from hex with a NSScanner but not sure how to go about converting Hexa-Tri-Decimal.

For example I have a NSString with "0XPM" the int value should be 43690, "1BLC" would be 61680.

¿Fue útil?

Solución

I can only think to do this using C strings, as they offer easier access to individual characters.

This seemed like an interesting problem to solve, so I had a go at writing it:

int parseBase36Number(NSString *input)
{
    const char *inputCString = [[input lowercaseString] UTF8String];
    size_t inputLength = [input length];
    int orderOfMagnitudeMultiplier = 1;

    int result = 0;

    // iterate backward through the number
    for (int i = inputLength - 1; i >= 0; i--)
    {
        char inputChar = inputCString[i];
        int charNumericValue;

        if (isdigit(inputChar))
        {
            charNumericValue = inputChar - '0';
        }
        else if (islower(inputChar))
        {
            charNumericValue = inputChar - 'a' + 10;
        }
        else
        {
            // unhanded character, throw error
        }

        result += charNumericValue * orderOfMagnitudeMultiplier;

        orderOfMagnitudeMultiplier *= 36;
    }

    return result;
}

NOTE: I've not tested this at all, so take care and let me know how it goes!

Otros consejos

Objective C is built on top of C, and luckily enough you can use the functions there to accomplish the conversion. What you're looking for is strtol or one of it's sibling functions. If I recall correctly strtol handles up to base36 (the hexa-tri-decimal you refer to).

http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top