• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

How do I manipulate hex values using C++?

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.
 
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"
 
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:
Back
Top