Dec to Hex

J

Josh Parker

What is a good way for me to convert a Decimal to Hexadecimal. I need
the number to be stored in a variable, it will not be printed to the
screen. Any help that can be provided will help. Thank you
 
M

Mike Wahler

Josh Parker said:
What is a good way for me to convert a Decimal to Hexadecimal. I need
the number to be stored in a variable, it will not be printed to the
screen. Any help that can be provided will help. Thank you

All values are stored in binary. "Decimal" and "Hexadecimal"
are *textual* representations which can be used for 'human
readable' input and output.

int i = 42; // stored 'internally' as 101010
std::cout << i << '\n'; // prints 42 (by default)
std::cout << std::hex << i << '\n'; // prints 2A


The following two statements have exactly the same effect:

int i = 42;
int i = 0x2A;

-Mike
 
D

David Rubin

Josh said:
What is a good way for me to convert a Decimal to Hexadecimal. I need
the number to be stored in a variable, it will not be printed to the
screen. Any help that can be provided will help. Thank you

All integer values are the same, regardless of the base. The only[1] time you
need to know the base is when you print (e.g., printf with %x) or convert (e.g.,
strtol with base 16). IOW, there is no difference between storing an integer as
a decimal (i.e., base 10) or hexadecimal value.

/david

[1] also when you read with scanf, but this is not recommended.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,431
Latest member
ElyseG3173

Latest Threads

Top