Search code examples
c++reinterpret-cast

how to convert char* pointer address to int in c++


how can i convert a char* address to int? in cygwin, i've got the error as follow:

test.cpp:31:80: 错误:从‘char*’到‘int’的转换损失精度 [-fpermissive] cout << "hex:0x" << setw(8) << left << hex << reinterpret_cast(&pchar[i])

(translate: Error, the conversion from ‘char*’ to ‘int’ will lose precision)

following is my source code:

int main()
{
    int num = 0x12345678;
    char *pchar = reinterpret_cast<char*>(&num);
    if (0x12 == *pchar)
    {
        cout << "big-end" << endl;
    }
    else if (0x78 == *pchar)
    {
        cout << "little-end" << endl;
    }
    else
    {
        cout << "wtf" << endl;
    }
    for (int i = 0; i < 4; ++i)
    {
        cout << "hex:0x" << setw(8) << left << hex << reinterpret_cast<int>(pchar + i)
            << "val:0x" << hex << static_cast<int>(pchar[i]) << endl;
    }



    return 1;
}

Solution

  • You can't: the behaviour would be undefined. This is because a char* is unrelated to an int.

    In your case why not use %p as the format specifier for the pointer? (Strictly speaking you should convert the argument to a void* or const void*).

    cout does this automatically for you:

    cout << (void*)(pchar);