c – atoi()等效于intptr_t / uintptr_t

C中是否有一个函数(C 11,如果它有所不同)将字符串转换为uintptr_t或intptr_t?我总是可以使用atoll()并在之后进行转换,但是对于32位机器和64位机器的32位机器来说,这样做会很好.

char* c = "1234567";
uintptr_t ptr = atoptr(c); // a function that does this;

最佳答案 这是IM中令人惊讶的IMO差距.虽然stringstream可以胜任这项工作,但对于这么简单的任务来说,它是一个非常繁重的工具.相反,您可以编写一个内联函数,根据类型大小调用strtoul的正确变体.由于编译器知道正确的大小,因此通过调用strtoul或strtoull来替换对函数的调用将足够聪明.即,如下所示:

    inline uintptr_t handleFromString(const char *c, int base = 16)
    {
         // See if this function catches all possibilities.
         // If it doesn't, the function would have to be amended
         // whenever you add a combination of architecture and
         // compiler that is not yet addressed.
         static_assert(sizeof(uintptr_t) == sizeof(unsigned long)
             || sizeof(uintptr_t) == sizeof(unsigned long long),
             "Please add string to handle conversion for this architecture.");

         // Now choose the correct function ...
         if (sizeof(uintptr_t) == sizeof(unsigned long)) {
             return strtoul(c, nullptr, base);
         }

         // All other options exhausted, sizeof(uintptr_t) == sizeof(unsigned long long))
         return strtoull(c, nullptr, base);
    }

如果您决定更改手柄的类型,这将很容易更新.如果你喜欢尖括号,你也可以做一些与模板等效的东西,虽然我没有看到它如何更清晰.

点赞