Writing Hex and Octal Values in C


Although base 10 is a convenient way to write numbers in a program, occasionally you'll want to write numbers in octal or hex (for int values).

Fortunately, C/C++/Java makes this simple.

Internal Representation

Suppose you write a statement like:
   int x = 0x23 ;
Does the compiler make a note that you save a hexadecimal value to an int variable?

The answer is no.

Let's see why. As you know, computers store information in binary. Suppose you write the following statement:

   int x = 12 ;
Do you think that the value 12 is saved in a memory location by storing the digits 1 and 2? Well, it's not. Instead, when the compiler compiled the code, it converted the 12 to a binary representation. In particular, it converted it to 2C.

However, you're not forced to think in 2C. You only have to think in base 10. Thus, language designers try to make it easy for you to write code in the representation that you're familiar with.

Neverthless, you should always be aware that anything you write in a program and gets executed eventually gets converted to binary.

To a computer, assigning x to 0x23 and assigning x to 35 is the same. Both get saved to the same 2C value. It doesn't matter than in the source code, that it was assigned as 0x23 or 35. That matters only to the compiler.

The compiler must recognize that 0x23 is hexadecimal, and convert it appropriately to 2C. Or it must recognize that it is 35, and again convert it to 2C. Either way, once it is in executable format, there's no information about how it got there. That information only resides in the source code.

Why is this important? Suppose you want to print out a number that was saved as 0x23. What would it print? Does it really make sense to print it as 0x23? In order to do so, this information would have to be recorded somewhere in the representation in the computer, and it's not. It's only recorded in the source code.

So, if you print out this value, you see 35. You'd only see 23 if you had the format set to print out hex.

How to Write a Negative Value

When you write 0x23, you might wonder how to negate it. Should you write the minus sign before the 0x, or after it? The answer is before. 0x indicates that the digits afterwards are written in hex. - is an operator, so it applies to a non-negative representation. Thus, you write -0x23.


Some summarizing facts: © 2003 by Charles Lin. All rights reserved.