C Programming Language Tutorial
Variables and Data Types
Input/Output
Looping and Selection Structures
Array
Functions
Preprocessing Command
Pointer
Structure
File Operations
Important Knowledge
In this tutorial, we'll discuss how to work with binary, octal, and hexadecimal numbers in the C programming language. These number systems are essential for understanding computer systems and low-level programming tasks.
To declare and initialize integer literals in binary, octal, or hexadecimal, use the following prefixes:
0b
or 0B
0
0x
or 0X
int binaryNumber = 0b1010; // 10 in decimal int octalNumber = 012; // 10 in decimal int hexadecimalNumber = 0xA; // 10 in decimal
To print integers in different bases, use format specifiers with the printf()
function:
%o
%d
%x
(lowercase) or %X
(uppercase)#include <stdio.h> void printBinary(int num) { if (num > 1) { printBinary(num / 2); } printf("%d", num % 2); } int main() { int number = 10; printf("Binary: "); printBinary(number); printf("\n"); printf("Octal: %o\n", number); printf("Decimal: %d\n", number); printf("Hexadecimal: %x\n", number); // Use %X for uppercase return 0; }
The output will be:
Binary: 1010 Octal: 12 Decimal: 10 Hexadecimal: a
That's it for our tutorial on binary, octal, and hexadecimal numbers in the C programming language. Understanding different number systems and how to work with them in C is essential for low-level programming tasks, debugging, and working with memory addresses or bitwise operations.
C program for converting decimal to binary:
#include <stdio.h> void decimalToBinary(int n) { if (n > 1) decimalToBinary(n / 2); printf("%d", n % 2); } int main() { int decimalNumber = 10; printf("Binary representation: "); decimalToBinary(decimalNumber); return 0; }
Converting binary to decimal in C program:
#include <stdio.h> #include <math.h> int binaryToDecimal(long long binaryNumber) { int decimalNumber = 0, i = 0, remainder; while (binaryNumber != 0) { remainder = binaryNumber % 10; binaryNumber /= 10; decimalNumber += remainder * pow(2, i); ++i; } return decimalNumber; } int main() { long long binaryNumber = 1010; printf("Decimal representation: %d\n", binaryToDecimal(binaryNumber)); return 0; }
C code for handling octal numbers:
#include <stdio.h> int main() { int octalNumber = 075; printf("Octal representation: %o\n", octalNumber); return 0; }
Manipulating hexadecimal numbers in C:
#include <stdio.h> int main() { int hexadecimalNumber = 0xA; printf("Hexadecimal representation: %X\n", hexadecimalNumber); return 0; }