### How to generate address of a variable into decimal integer

Hi everyone.
First, let me give a special THNX to people who helped me in my earlier topics.

I was wondering how can i generate a hexadecimal number that is taken from the address of a variable into a usable integer?

Here is the code :

 ``12345678910111213141516171819202122232425`` ``````#include #include using std :: cout ; int HexToDec (int &) ; int main () { int Dec , a ; Dec = HexToDec (a) ; cout << Dec ; getch () ; cout << & a ; getch () ; } int HexToDec (int & Hex) { int HexTranslator ; short i = 0 ; while (Hex) HexTranslator = (16 * i) * (Hex % 16) , Hex /= 16 , i++ ; return HexTranslator ; }``````

 ```-336 0012FF54```

Well, as you see I print the address of a in output and it is 0012FF54, but the HexToDec function doesn't work.
Here is a complete description of my problem and it's reason :
My problem is simply converting a Hex to Dec.
Believe me, I googled for it, but every result was just about HexaDecimal in a string, I men they said put your HexaDecimal number into a string, but I have no idea hoiw to convert 0x0012FF54 into a string and if I had an Idea about it, I still wouldn't do it. I preferred to convert directly from Hex to Dec (IF POSSIBLE)
ANd the last problem is in the HexToDec function.
I said HexTranslator = (16 * i) * (Hex % 16) But I'm not sure if the VS2010 understands the (Hex % 16) is a Hex. (And doesn't encounter a problem if it was F) THank you so much. Sorry if my English is terrible and sorry if my topic was a little against the rules of the forum
Last edited on
To put it simply, you can't modify memory location values like how you want. There is also numerous logical errors with your function. You're passing the variable by reference, meaning, it's still just an int, but whatever you do to it, will reflect back in main. Your math is wrong when attempting to convert hex to decimal, mainly because each pass, you're starting over at 0 for HexTranslator, essentially.

The reason that you saw everywhere online suggest to converting from string is because hexadecimal is a standard number system in C++. Meaning, you can assign an int a hex value, 0x224532, and display it on the screen, and it's decimal conversion is automatically shown instead. This causes problems since you can't physically store a hex value.

The smart way to go is to store it in a string and manually parse the string. string[0] would be the far left digit so once you convert that, you need to make sure that you shift your int so that you don't accidentally overwrite it.

Good Luck.
 ``1234`` `````` int a; int Dec = (int) & a; cout << & a << endl; cout << Dec << endl;``````

The variable `Dec` will hold the value of the address of `a`.
Internally this is stored in binary format, since that's the normal way that integers are handled.

The two `cout` statements each perform a conversion to a human-readable format. The default representation of an address is to show it in hexadecimal, while the default representation of an integer is to show it in decimal.

Perhaps simply cast the address to an integer as part of the cout statement:
 `` `` `` cout << int (& a) << endl;``
> generate a hexadecimal number that is taken from the address of a variable into a usable integer?

There is no certainty that an `int` would be large enough to hold the numeric value of the address of an object.
Use `std::uintptr_t` instead:

 ``12345678910111213`` ``````#include #include int main() { int var = 7 ; int* ptr = &var ; std::uintptr_t ptr_val = std::uintptr_t(ptr) ; std::cout << std::dec << ptr_val << '\n' ; // print it as a decimal number std::cout << std::hex << std::showbase << ptr_val << '\n' ; // print it as a hex number }``````
@Volatile Pulse Thank you! Actually I learned a lot and yeah you were right! I didn't plus the HexTranslator to it's previous value.

@Chrvil I just can say LOL! I didn't even think about the type casting. Thank you! That is exactly what I wanted.

@JLBorges actually it was TOO complicated for a beginner. I know nothing about cstdint and std :: uintptr_t . But Thank You. I will come back and read them wen I learned about them.

But after this question I facedanother problem using them in functions. I will describe it to you later. Should go. Thank you all again.
@AIVIO
JLBorges tends to have correct answers, but they are almost always over beginners' heads, and usually mine. A lot of the comments he makes demonstrate code that I've never even seen before. That's necessarily a bad thing, but I believe it's typically more to show off what he knows, and possibly hoping that others will learn as well. Overall, I believe it's a little too advanced for the beginner thread.

Something else you may not know. A user is allowed to enter a hexadecimal number for an int, long, etc., however, it will be displayed in the default format, which is decimal. So if the user enters 0x00000F, when you go to display that, 16 will appear on the screen (Don't mark my words since I just got home and haven't had time to try it). That's why, in order to do it properly, you need to either pass a string, or individual characters, to properly create a Hex-to-Dec function.

@JLBorges
You've been gone for a while, and all of a sudden I see you pop up with some features I've never seen before, not only here, but another thread or two I participated in. Although your answer is appreciated, and albeit the more efficient way to go, the problems that most beginners get isn't to find the easiest way, but to understand how everything works, i.e. reading a hex number and being able to convert it as well. There is plenty of functions and features out there that make our lives easier, but one of the early steps in programming is understanding the basics so when it comes time to use these advanced features, you appreciate what's already there for. I'll now direct you to www.thedailywtf.com

The website demonstrates how a lot of "programmers" don't understand the basics, and haven't learned how to use advanced features because of the same issue. They tend to write horribly written code due to never learning the proper way or just expanding your mind. One thing to note is that there are only a few C++ stories on there, that I've run into this far, which either means that C++ programmers are a step ahead of other language programmers, it's a harder field to get into, or it's just used far less than the other languages on the site, JAVA, VB, SQL (duh!), etc.
@Volatile Pulse Thank you again.

I have another question. Is there any way to do srth. that the program gives another location to the same variable the previous time it gave on RAM. I mean suppose that you have an
`int a`
and you do
`cout << & a ;` .
So, the compiler will print out sth. like this :
 `00E564FA`

But I want to do sth. that (for example) when I run the program now, it is 00FE45A3 and I close the program and open it again and it is another thing, for example 007654AB . Is there any algorithm to do such a thing?

And another question? What is the function for generating random numbers? in which header file is it?
Coming soon ...
Last edited on
Is it possible? Yes. Do I know how to do it? Not really. I mean, you can probably open and close a few other applications and it will change what RAM is available, but I don't really know how all of that works and I believe it comes down to the OS's architecture.

Why do you want to do that? Granted, let's say that you want to try to get the variable to have the same memory location every time. There is several issues with that.

1) Every time that you run your program, that memory location might be in use by another program or your OS. Trying to access that information will signal errors and eventually your program will crash (the purpose behind this is to "prevent" malicious programs, or unintentional programs, from modifying other program information). The OS has strict rules on what can access other program memory, and typically it's just not allowed.

2) Even if you manage to get the same memory location each time, you're not even guaranteed that it had the same value stored in it from even 5 seconds ago. Depending on your system, your RAM might flash itself, your compiler might set a default value for said variable, or even another program could have used that memory since you last used it.

3) It would serve no purpose to your program which memory location you actually got. We don't build out applications around the memory locations, just that we may need to allocate x amount of memory for doing y.

With those three things, I can also apply it to manually changing the memory locations each time.

1) Sometimes you just get what you're handed. If memory location x is available every time your program runs, and your program is forced to use it, sucks to be you.

2) Even if you can find a way to change the location, it wouldn't serve any purpose to the information that's in it. Let's say you just did a fresh restart of your computer. That memory may not have even been touched yet, let alone countless other locations. They would be nothing in there, garbage values, etc.

3) Let's say you find someway to do it, and find a use even after the above steps. Where would you possibly ever need this? The garbage values stored at that location won't help you fix anything. Programs that rely on secretive information can manually change the values before exiting. You can't access them while they're running anyways. The memory location itself really doesn't matter, not that I've ever seen.

With all of that, I wouldn't see why you would need such a thing. I'm not a computer science major by any means, but I believe I've explained that correctly (I'm sure someone will correct me if I didn't). The thing that matters about memory locations is that we have the correct number of consecutive blocks of memory for a certain object. Typically, the only other time memory location actually matters is during debugging and if you're interested in seeing how things work.

This is getting into the deeper end of computers, and something I'm not comfortable with, actually, I'm not comfortable with any of the stuff I covered this far.

Something, however, that I can help you with is the rand() function. It's located in cstdlib and you can read more about it here: http://www.cplusplus.com/reference/cstdlib/rand/

Please note: Before using rand, it's typically practical to use the srand function to seed it. rand isn't actually random numbers, and seeding only tells the compiler which set of numbers to read from. Now, that can be a conversation in itself, but most commonly, srand is placed at the very beginning of main (the only function that shouldn't be called more than once) and is passed the parameter of time(0). time can be found in the ctime header. Again, long story short, it returns the number of seconds from when your program was launched since 1/1/1970. It's unlikely you're going to run your program twice in a second, so it's a good "random" seed.

Without seeding, you will get the same "random" numbers.

Hope all of this helps.
 ``123`` ``````short Number1 [MAX] ; for (short i = 0 ; i < MAX ; i++) Number1 [i] = getch () ;``````

This is only legal if MAX is defined as a const and has a value greater than 0 and can be converted into an unsigned int. getch() is located in a header file named conio.h, but isn't part of the standard libraries and each version can have varying resullts. I believe VS suggests using cgetch() or something similar, saying that getch() is deprecated.

Regardless, it comes down to it not being standard, and although getch() is useful, at times, it's recommended against using, along with anything else that's included in the conio.h header. Instead, there is a function that Duoas, a member on this forum, wrote that I have converted into, as close as I could, a windows specific version of getch(). It uses windows.h, which is rather large, but will work the same on all windows versions, that I'm aware of. The code is:
 ``123456789101112131415161718192021222324`` `````` int getch() { /* Windows */ HANDLE hConsole; INPUT_RECORD inrec; DWORD count, mode; // Set the console mode to no-echo, raw input, and no window or mouse events. hConsole = GetStdHandle(STD_INPUT_HANDLE); if (hConsole == INVALID_HANDLE_VALUE || !GetConsoleMode(hConsole, &mode) || !SetConsoleMode(hConsole, 0)) return 0; FlushConsoleInputBuffer(hConsole); // Get a single key RELEASE do { ReadConsoleInput(hConsole, &inrec, 1, &count); } while ((inrec.EventType != KEY_EVENT) || inrec.Event.KeyEvent.bKeyDown); // Restore the original console mode SetConsoleMode(hConsole, mode); return inrec.Event.KeyEvent.wVirtualKeyCode; /* Windows */ }``````

There is also Linux code, but I haven't gotten around to properly converting it yet. Here is the link to the original version: http://www.cplusplus.com/articles/iw6AC542/
Note: It's located under the OS Specific Ways
> @JLBorges actually it was TOO complicated for a beginner.
> I know nothing about cstdint and std :: uintptr_t .

The basic idea isn't too complicated (even if cstdint and std :: uintptr_t is).
It is this (and it is very important for a beginner to realize this):

An `int` in C++ is a whole number like an integer in mathematics. But it is not the same - it cannot represent any integer, it has a finite range, a minimum and a maximum value that can be represented. For instance, 1000000000000 is an integer, but an `int` may not be big enough to hold that value.

Try this:
 ``1234567891011`` ``````#include int main() { int number = 2 ; for( int j = 1 ; j < 65 ; ++j ) { std::cout << "2 ^ " << j << " == " << number << '\n' ; number = number * 2 ; } }``````
AIVIO wrote:
actually it was TOO complicated for a beginner. I know nothing about cstdint and std::uintptr_t

You should learn about them if you're planning to convert an address into a number. There is no other way that is guaranteed to work.
Thank you all. With the help of you three persons, I now know how addresses and variables work, a thing that lots of beginners do complicate them and don't know why, where and how to use them.

@Volatile Pulse
WOW! Thank you! I do understand how hard it is to type all that thing. I don't know how to thank you. But, YES, I do have a purpose to know the addresses and change them. I have nothing to do with the values in the addresses.
Volatile Pulse :
 Without seeding, you will get the same "random" numbers.

It is the exact reason for me to do that and it is the same reason for creating this topic. I have discovered an algorithm to genereate random numbers using the address of a data in an algorithm of type int depending on the number the user enters (It is the same known as range). And the reason of my question:
 How can I do something that the variable get another address? Not the same address the last time it got
And from the time I created this topic I found out the useless values that are stored in the RAM from the last apps are useful for generating REAL RANDOM NUMNBERS. So currently I am trying to do sth. that the program creates a maximum of 10 files (each MAX 2 kb) in a location for 2 reasons: 1- Create random numbers in the RAM (known as garbage values) 2- Ocuppy the RAM, so the pointer of our array can't get the same memory address as the last time.

Thank You again.

@JLBorges
Nice example. Another thing that beginners don't know much about is varibala data types. (And tha's why they (and people like me) always use int for every purposes.)
Now you helped me understand them. Now I know what exactly int takes 4 Bytes or long double takes 8 Bytes means. And that is the reason the int doesn't go more than 2 ^ 32 - 1 or long double doesn't get larger than 2 ^ 1024 - 1
Thank You too.

@Cubbi
Yeah you're right. I made a mistake and that is I only read the documentation part and haven't ever looked at references.

And at last:
Thank you all again. I'll be working more on my code to see whether can I do such a thing (generating random numbers) or not and I will let you know more about my progress.

(Unrelated to topic)
@Volatile Pulse
I didn't explain my second question (The unrelated one to topic) good and that's why you didn't answer me right, I mean you said something else.
My main question was about `Number [i] = getch () ;` It didn't get the input and I found out why and fixed taht. But now I have another question:
 ``1234567891011`` ``````while (1) { C2 [i] = getch () ; cout << C2 [i] ; if (C2 [i] == '\n') break ; S2 [i] = CharToShort (C2 [i]) ; i++ ; if (i >= MAX) break ; }``````

The first if is never wxecuted. I mean when I press Enter, it jumps over the if condition. Why is that?

And again thank you all.
Stupid internet cutting out before my response was submitted. But to make my 3k character post shorter, I believe that getch() returns the int value of the corresponding key on your keyboard. However, you're trying to compare the ENTER key. On windows systems, the ENTER key isn't '\n', it's defined as "\r\n" I believe, meaning that the first key your get will either be '\r', 0, 224 or possibly some other value. I don't remember exactly how it all works out, but see if changing '\n' to '\r' works.

@JLBorges
I had a long apology typed up and don't feel like retyping the entire thing. However, I wanted to say sorry if my post was ill mannered. I respect you, and most of the other senior members on this site. Sometimes, I just get carried away and blurt out things without using my filter. I went back and researched all of the stuff you talked about on this thread and learned a lot, even stuff that proved my other responses wrong.

I have this need to learn as much as I can, but I also have this lack of drive to learn on my own. I tend to learn best when someone puts effort into at least trying to explain it and I tend to disregard just about everything else as someone not willing to teach. Again, I'm sorry.

Alas, I need to stop trying to be so quick to answer everything and sit and evaluate everything before posting, especially if it's something I'm not 100% on.
 ``3456`` `````` C2 [i] = getch () ; cout << C2 [i] ; if (C2 [i] == '\n') break ;``````

I think here the key recorded when the [enter] key is pressed is probably the carriage-return rather than the newline character. At any rate on my machine that's what happens. `<conio.h>` and `getch()` are non-standard, so I don't know whether that's always the case.

You could try this:
 `` `` `` if (C2 [i] == '\r')``

or to be safe, this:
 `` `` `` if (C2 [i] == '\r' || C2 [i] == '\n')``

As a background comment, on windows machines, in a text file a newline is usually represented by the pair of characters "\r\n" or CR-LF, the carriage-return+linefeed pair. Other operating systems usually use a single '\n' character.
@Volatile Pulse I know you weren't addressing me, so there's no need to take my reply seriously. It's just that recently I've seen one or two 'helpful' replies from absolute beginners, which have sometimes missed the mark.

I was briefly tempted to respond to such posts in a critical way. But then all of us make replies in good faith. More than once after reading other replies I realised the other answers were better than the one I gave. Sometimes that's been a spur for me to do some more research on various topics.

I think it can be a case of not knowing what it is that you don't know - the unknown unknowns, and that's something which on occasion can probably get all of us, one way or another.
And Thank you again. Yes! the '\r' works instead of '\n' .
OS's make programming much more complicated than it is.

Topic Closed!
Topic archived. No new replies allowed.