Lucy Gu
Lucy Gu

Reputation: 395

Convert char* to int memory address

I have:

char* mem = (char*) 0xB8000;

Then mem is passed to a function. Inside the function, I want to get the number 0xB8000 back and compare it to some other integers. How do I convert mem back to the original integer?

Upvotes: 1

Views: 616

Answers (2)

Jan Schultke
Jan Schultke

Reputation: 39424

To convert any pointer to an integer, do the following:

#include <stdint.h>

uintptr_t ptr_to_integer(const void *ptr) {
    return (uintptr_t) ptr;
}

Note that the size of uintptr_t might vary between platforms. Also this is an optional part of the C standard, so technically only uintmax_t would be absolutely portable.

Upvotes: 3

chux
chux

Reputation: 153338

How do I convert mem back to the original integer?

Usually a cast to (u)intptr_t will form the original integer.

include <stdint.h>

printf("o: %lX\n", 0xB8000LU);
char* mem = (char*) 0xB8000;
printf("mem %p\n", (void *) mem);
uintptr_t i =  (uintptr_t) mem;
printf("i: %jX\n", (uintmax_t) i);

Pitfalls

Round tripping (u)intptr_t to void * to uintptr_t (or any integer type) is not specified by C to result in the original value. Even void * to (u)intptr_t to void * is only specified to return an equavalent pointer, not necessarily the same pointer bit pattern.

Casting an arbitrary number like (char*) 0xB8000 to a pointer is not specified to work.

"the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation" C17dr 6.3.2.3 5

(u)intptr_t are optional types - though common. A compliant library may not be able to provide the type.

No corresponding print specifier for (u)intptr_t. A reasonable work-around is to to covert to the widest available type and print.


I want to get the number 0xB8000 back and compare it to some other integers.

A better approach could covert the "other integers" to a char * and compare pointers.

Best for OP to post the larger code usage to handle the overall goal.

Proceed with caution.

Upvotes: 2

Related Questions