Hex character to int in C++

前端 未结 4 666
猫巷女王i
猫巷女王i 2021-01-14 01:20

How can I change a hex character, not string, into a numerical value?

While typing this question, I found many answers on how to convert hex strings to values. Howe

4条回答
  •  滥情空心
    2021-01-14 01:55

    The ternary from levis501 can be expanded to:

    int v = (c >= 'A') ? (c >= 'a') ? (c - 'a' + 10) : (c - 'A' + 10) : (c - '0');
    

    But if you want error checking it gets a bit messy:

    int v = (c < '0')  ? -1 :
            (c <= '9') ? (c - '0') :
            (c < 'A')  ? v = -1 :
            (c <= 'F') ? (c - 'A' + 10) :
            (c < 'a')  ? v = -1 :
            (c <= 'f') ? (c - 'a' + 10) : -1;
    

    It doesn't look much better in if-else blocks:

    int v = -1;
    if ((c >= '0') && (c <= '9'))
        v = (c - '0');
    else if ((c >= 'A') && (c <= 'F'))
        v = (c - 'A' + 10);
    else if ((c >= 'a') && (c <= 'f'))
        v = (c - 'a' + 10);
    

    Since I wanted a fast implementation and validation, I went for a lookup table:

    int ASCIIHexToInt[] =
    {
        // ASCII
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
         0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
        -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    
        // 0x80-FF (Omit this if you don't need to check for non-ASCII)
        -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
        -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
        -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
        -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
        -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
        -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
        -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
        -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
    };
    

    In this case it's just:

    int v = ASCIIHexToInt[c];
    if (v < 0)
        // Invalid input
    

    Runnable examples are (hopefully) here and here.

提交回复
热议问题