Convert to/use hexadecimal numbers

Is there a way to pass a hex value to an array element? I've been unable to find anything other than how to modify a stream such as

for (int i=0; i<1024; i++)
{
cout<<hex<<i;
}

but I need to modify the value I pass to an array (the value is to represent a memory address in a virtual memory simulation) and that value can't be a string as I need to compare it and search it as a number, a hexadecimal integer.

To clarify, how do I modify/implement the following code to pass the variable i in hexadecimal form to my array?

int memory[1024];

for (int i=0; i<1024; i++)
{
memory[i]=hexadecimal_verision_of_integer_i;
}


Huge thank for any help you can offer me.
Hexadecimal is just a way to display the number. It has nothing to do with how the number is actually stored.
Thanks Peter87 but I do understand that. Sorry I wasn't terribly clear in my post but as I mentioned in the array is meant to simulate a memory system and thus it displays addresses in hexadecimal. The program is meant to output a log file which will display hexadecimal addresses. Can you help at all? Is there a function you know which will handle to conversion?
I don't understand why you can't use std::hex as you do in the first code snippet when you print the memory value?
closed account (o3hC5Di1)
Hi there,

Peter87 undoubtedly knows more than I do, but here's what I think you may need:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
    int i = 1024;
    char val[3];
    sprintf(val, "%x", i);
    
    cout << val;
    return 0;
}


sprintf with %x will display the int as hex and write it to a string, allowing you to store that string into the array.

Hope that helps,

All the best,

NwN
Last edited on
Thanks so much for your help guys. Peter87 you are right, I was over engineering the solution and it makes much more sense to do the conversion at the end! I have another issue however which is to do with reading hex numbers in from a .txt file but I think I should start a new threat for that
closed account (o3hC5Di1)
Just out of interest, would you mind sharing your solution? :)

Thanks,

NwN
No problem NwN I will do so as soon as I have the whole program put together :)
Topic archived. No new replies allowed.