C++ – Converting from unsigned Char* to unsigned int

ccompiler-errorstypes

When I do the following, I get this error:

../src/Sample.cpp:19: error: cast from \u2018UINT8*\u2019 to \u2018UINT8\u2019 loses precision

#include <iostream>
using namespace std;

typedef unsigned char UINT8;
typedef unsigned int UINT32;

#define UNUSED(X) X=X

int main() {
    UINT8 * a = new UINT8[34];
    UINT32 b = reinterpret_cast<UINT8>(a);

    UNUSED(b);

    return 0;
}

How would I go about solving this. Keep in mind I am not trying to convert string to unsigned long, rather converting char* (the ADDRESS value ) to int.

Thanks

Solution:

Turns out that this problem has to do with the pointer size. On a 32 bit machine, the pointer size is 32 bit, and for 64 bit machine is of course 64. The above wont work on a 64 bit machine, but will on a 32 bit machine. This will work on a 64 bit machine.

#include <iostream>
#include <stdint.h>

using namespace std;

typedef  uint8_t UINT8;
typedef int64_t UINT32;

#define UNUSED(X) X=X

int main() {
    UINT8 * a = new UINT8[34];
    UINT32 b = reinterpret_cast<UINT32>(a);
    UNUSED(b);

    return 0;
}

Best Answer

Assuming that sizeof(int) == sizeof(void*) you can use this code to convert:

int b = *reinterpret_cast<int*>(&a);

or variations thereof. I think static_cast will work too.

Of course a has to be l-value (able to be assigned to) to get the address of it. For non-l-values, you need to use a function and the good old union trick will work:

int Pointer2Int (void* p)
{
    union { void* p; int i; } converter;
    converter.p = p;
    return converter.i;
}