hello!

i'm doing some memory altering but i've come to an standstill. here is my problem:
(ill try to write it as an example somwhow..)

i have an int (lets say int x). this int has an value of an memory address but in decimal
not in hex value. now i want to convert this decimal value into hex (lets say i have an int pointer (int *y). i want this y to be y=(int*)0xmemory_address_from_int_x_that_is_converted_to_hex
how can i convert that int x from decimal to hex and store it into y??

Dani AI

Generated

Good catch by — “decimal vs hex” is only a way to print a number. A few important practical details follow so the cast you tried is safe and portable.

On modern platforms you must not use int to hold addresses (it may be too small on 64-bit). Prefer the integer types designed for pointer storage: std::uintptr_t / std::intptr_t from <cstdint>. In C++ use reinterpret_cast (not a C-style cast) when converting between an integer-holding-address and a pointer. Example:

#include <cstdint>
#include <iostream>
#include <iomanip>

std::uintptr_t addr = /* decimal address value you have */;
int* p = reinterpret_cast<int*>(addr);

std::cout << "address: 0x" << std::hex << addr << std::dec << '\n';
std::cout << "pointer (as void*): " << static_cast<void*>(p) << '\n';

Cautions and practical tips:

  • Do not dereference p unless that address is valid in your process and properly aligned; doing so can crash or produce undefined behavior.
  • Converting arbitrary integers to pointers is implementation-defined; the round-trip (pointer -> uintptr_t -> pointer) is the portable pattern.
  • For byte-level memory work, use unsigned char* or std::memcpy to avoid strict-aliasing issues.
  • If you intend to read/write another process’s memory, use the OS APIs (e.g., Read/WriteProcessMemory on Windows, ptrace//proc/<pid>/mem on Unix) with appropriate privileges — you cannot safely dereference foreign addresses directly.

Finally, on 64-bit builds check your types. What worked as a quick test on 32-bit may silently break or truncate addresses on 64-bit systems.

Recommended Answers

All 2 Replies

decimal or hex makes no difference, since it's all binary to the machine.

int x = 10;
int *y = (int*)x;

y is now 0xa, without you having to do anything special at all.

ty very much. never thought it would work like that :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.