简体   繁体   中英

Converting from unsigned Char* to unsigned int

When I do the following, I get this error:

#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;
}

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;
}

This isn't a good idea, but the line should read:

UINT32 b = reinterpret_cast<UINT32>(a);

reinterpret_cast takes the type of the destination type as the template parameter.

With the correct type g++ will tell you that it isn't a good idea:

error: invalid cast from type ‘char’ to type ‘int’

see Cthutu's answer for a more correct approach.

An option would be to :

int *a; char b[64]; int c;

a = (int*) malloc (sizeof(int));

sprintf(b, "%d", a);

c = atoi(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM