Different Types of Number Systems in C Language - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Different Types of Number Systems in C Language

Share This
You are familiar with different types of number systems, like, Binary, Octal, Hexadecimal, and Decimal systems. In previous tutorials, we have taken a decimal number system. Here, we will discuss how to work with other number systems.

In the following example, we have taken three integer variables, x, y, and z. Here, x is a decimal number, whereas y is an octal number and z is a hexadecimal number.

An octal number starts with 0 and a hexadecimal number starts with 0x.

The data type for octal and hexadecimal numbers is integer (int).


#include <stdio.h> int main(void) { int x = 111; /* Decimal number */ int y = 057; /* Octal number */ int z = 0xAB; /* Hexa Decimal number */ float f = 12345E-2; printf("%d\n", x); printf("%d\n", y); printf("%d\n", z); printf("%f\n", f); return 0; }

Output 



Working with Octal Number System 


To take an octal number as input, you have to use %o instead of %d. It's the same for printing the output, as shown in the following sample program.

#include <stdio.h> int main(void) { int x; int o1; int o2; printf("-----Input-----\n"); scanf("%d", &x); scanf("%o", &o1); scanf("%o", &o2); printf("-----Output in octal format -----\n"); printf("%o\n", x); printf("%o\n", o1); printf("%o\n", o2); printf("-----Output in decimal format -----\n"); printf("%d\n", x); printf("%d\n", o1); printf("%d\n", o2); return 0; }

Output 


Working with Hexadecimal Number System 


To take a hexadecimal number as input, you have to use %x or %X instead of %d. It's the same for printing the output, as shown in the following sample program.

#include <stdio.h> int main(void) { int x; int h1; int h2; printf("-----Input -----\n"); scanf("%d", &x); scanf("%x", &h1); scanf("%x", &h2); printf("-----Output x in hexadecimal format -----\n"); printf("%x\n", x); printf("%X\n", x); printf("-----Output in hexadecimal format -----\n"); printf("%x\n", h1); printf("%X\n", h1); printf("%x\n", h2); printf("%X\n", h2); printf("-----Input -----\n"); scanf("%X", &h1); scanf("%X", &h2); printf("-----Output in hexadecimal format -----\n"); printf("%x\n", h1); printf("%X\n", h1); printf("%x\n", h2); printf("%X\n", h2); return 0; }

Output 




Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.