How do I manipulate hex values using C++?

Onceler

Golden Member
Feb 28, 2008
1,262
0
71
Every search I do on google comes up with how to convert hex into decimal.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
How do you want to manipulate them? Every value is a set of bits in one or more registers. Hex is just one way to look at those bits, as decimal is another way, and octal a third. Are you trying to perform arithmetic operations? Or format a string representation? You need to learn to give more context and detail in your posts if you want helpful responses.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
To print them:
Code:
int val = 16;  // decimal
cout << hex << val << dec << endl; // prints "10"

To form immediates:
Code:
int val = 0x10;  // hex immediates start with 0x
cout << val << endl; // prints "16"
 

Leros

Lifer
Jul 11, 2004
21,867
7
81
Computers do all their arithmetic in binary. We generally use decimal when we write code, just because its the easiest for us to understand. There is nothing stopping you from using hex or even binary numbers when you write code.

The following lines generate the exact same code:

Code:
byte a = 10; //decimal
byte a = 0x0A;  //hex
byte a = 0b00001010; //binary

You can do the same kind of thing with shorts, ints and longs too. Any numbers.

So to work with hex, you would just write your numbers in hex and prefix them with "0x". Everything else is the same

Example:
Code:
//decimal
short a = 10;
a = a + 4;
is the exact same as:
Code:
//hex
short a = 0x000A;
a = a + 0x0004;
is the exact same as:
Code:
//binary
short a = 0b0000000000001010;
a = a + 0b0000000000000100;
 
Last edited: