How To: Represent Numbers in Dec, Hex, and Oct

Introduction

In C and C++, you can have 3 ways of write a number:

  • Using Decimal (base-10) notation
    Very nice for general numbers. It’s easy to read and maintain. Read about decimal notation here.
  • Using Hexadecimal (base-16) notation
    Very efficient for flags especially if you need to see how bits are organized. Plus, it is very popular in C and C++. Read about hexadecimal notation here.
  • Using Octal (base-8) notation
    Not very friendly for most developers and for team mates of course. Read about octal notation here.

Unfortunately, you cannot write a binary number directly in your code. Convert it to any of the three notations first. Read about binary notation here.

Decimal Representation

Just as you write number on papers, you can write it in your code.

	int i = 100;

And you can use the format specifier %d to display the number as decimal using the printf function and its €œsisters€ (e.g. wsprinf in Windows).

	printf("%d", i);

Hexadecimal Representation

Just convert the number to hex and write it prefixed with 0x.

	int i = 0x64;

And you can use the format specifier %x to display the number as hexadecimal as small letters. And %X to display it as capital letters.

	printf("0x%x", i);

Octal Representation

Convert the number to oct and write it prefixed with 0.

	int i = 0144;

Of course, you can use printf to display octal numbers. And this is done through the %o format specifier.

	printf("%o", i);

Beware while reading octal numbers. Octal representation is very similar to decimal. 0144 equals to 100 in decimal notation and 0x64 in hexadecimal.

Unfortunately, you can’t use printf to display numbers in binary notation. You can make your own routine that accomplishes that.

Similar Posts:

Random Posts:

Recent Posts: