Welcome to our blog on how to convert a number to binary in C. Converting numbers to binary is a crucial step in many programming tasks, such as working with bitwise operations, encoding data, and understanding computer architecture.
In this blog, we will explore different approaches and sample problems as well. You are a beginner or an experienced programmer does not matter because this blog will help you understand how to perform this essential operation in C and unlock the full potential of binary representation in your programming projects.
Why is converting numbers to binary in C is needed?
Converting numbers to binary in C is needed for several reasons are:
- Bit-level manipulation: In C, you can perform bitwise operations on binary numbers, such as AND, OR, XOR, and shifting. Converting numbers to binary enables you to perform these operations at the bit level, which can be useful in tasks like data manipulation, encryption, and graphics processing.
- Device communication: Many hardware devices communicate with the computer using binary data, such as sensors, actuators, and communication protocols.
- Algorithm implementation: Several algorithms and data structures, such as bitwise operations, binary search, and bitwise manipulation, rely on binary representation.
How To Convert Number To Binary In C
Here are six different approaches to how to convert number to binary in C with detailed solution steps, code, and output for each approach:
- Bitwise Shifting
- Bitwise AND with Mask
- Division and Remainder
- Recursion
- Bitset
- String Manipulation
Let’s dive in more with examples to each approach.
Approach 1: Bitwise Shifting
This approach uses bitwise shifting to extract each bit from the given number and prints it to obtain the binary representation.
Pros:
- Efficient and fast, as it involves only bitwise operations.
- Suitable for large numbers.
- Simple and easy to understand.
Cons:
- Assumes a fixed-size integer (typically 32 or 64 bits) for the number.
- May not work correctly for negative numbers.
- Output may include leading zeros for smaller numbers.
Code:
#include <stdio.h>
void convertToBinary(int num) {
int numBits = sizeof(num) * 8;
for (int i = numBits - 1; i >= 0; i--) { // Iterate from the most significant bit to the least significant bit
int bit = (num >> i) & 1; // Shift the bits to the right and perform bitwise AND with 1 to get the current bit
printf("%d", bit);
}
printf("\n"); // Add a newline character after printing binary representation
}
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("Binary representation: ");
convertToBinary(num);
return 0;
}
Output:
Input: 22
Output: 00000000000000000000000000010110
Code Explanation
- sizeof(num) * 8 – 1 calculates the number of bits in the integer type (assuming 32 or 64 bits) and starts from the most significant bit (MSB).
- (num >> i) & 1 shifts the bits of num to the right by i positions and performs bitwise AND with 1 to get the current bit.
- The current bit is then printed using printf() to obtain the binary representation.
Approach 2: Bitwise AND with Mask
This approach uses bitwise AND with a mask to isolate each bit from the given number and prints it to obtain the binary representation.
Pros:
- Efficient and fast, as it involves only bitwise operations.
- Suitable for large numbers.
- Can handle negative numbers correctly.
Cons:
- Assumes a fixed-size integer (typically 32 or 64 bits) for the number.
- May not work correctly for numbers with leading zeros.
- Requires additional steps to handle negative numbers.
Code:
#include <stdio.h>
void convertToBinary(int num) {
int numBits = sizeof(num) * 8;
for (int i = numBits - 1; i >= 0; i--) { // Iterate from the most significant bit to the least significant bit
int bit = (num >> i) & 1; // Shift the bits to the right and perform bitwise AND with 1 to get the current bit
printf("%d", bit);
}
printf("\n"); // Add a newline character after printing binary representation
}
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("Binary representation: ");
convertToBinary(num);
return 0;
}
Output:
Input: 12
Output: 00000000000000000000000000001100
Code Explanation:
- 1 << sizeof(num) * 8 – 1 creates a mask with only the most significant bit (MSB) set to 1, by shifting 1 to the left by the number of bits in the integer type (assuming 32 or 64 bits) minus 1.
- (num & mask) performs bitwise AND between the number and the mask to isolate the current bit.
- If the result is non-zero, it means the current bit is 1, and if the result is zero, it means the current bit is 0.
- The current bit is then printed using printf() to obtain the binary representation.
Approach 3: Division and Remainder
This approach uses division and remainder operations to repeatedly divide the given number by 2 and obtain the binary representation by collecting the remainders.
Pros:
- Suitable for any size of numbers, including negative numbers.
- Does not require bitwise operations, making it more portable across different architectures.
- Simple and easy to understand.
Cons:
- May not be as efficient as bitwise approaches for large numbers.
- May involve more operations for numbers with leading zeros.
- Requires additional steps to handle negative numbers.
Code:
#include <stdio.h>
void convertToBinary(int num) {
int binary[32]; // Assuming integer is 32 bits
int i = 0; // Index for binary array
while (num != 0) {
binary[i++] = num % 2; // Get the remainder when divided by 2
num /= 2; // Divide the number by 2
}
// Print the binary representation in reverse order
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
}
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("Binary representation: ");
convertToBinary(num);
printf("\n");
return 0;
}
Output:
Input: 25
Output: 11001
Code Explanation:
- The binary array is used to collect the remainders obtained from successive divisions of the given number by 2.
- The loop continues until the number becomes 0.
- The remainders are collected in reverse order in the binary array.
- The binary representation is then printed by iterating through the binary array in reverse order.
Approach 4: Recursion
This approach uses recursion to convert the given number to binary by repeatedly dividing it by 2 and concatenating the remainder obtained from the recursive calls.
Pros:
- Suitable for any size of numbers, including negative numbers.
- Provides a clean and concise solution using recursion.
- Can easily handle different base conversions with minor modifications.
Cons:
- May not be as efficient as bitwise approaches for large numbers.
- May involve more function call overhead for very large numbers.
- Requires additional steps to handle negative numbers.
Code:
#include <stdio.h>
void convertToBinary(int num) {
if (num > 1) {
convertToBinary(num / 2); // Recursive call with num divided by 2
}
printf("%d", num % 2); // Print the remainder when divided by 2
}
int main() {
int num;
printf("Enter a decimal number: ");
scanf("%d", &num);
printf("Binary representation: ");
convertToBinary(num);
printf("\n");
return 0;
}
Output:
Input: 15
Output: 1111
Code Explanation:
- The function convertToBinary() is called recursively with the number divided by 2 as the argument.
- The base case is when the number becomes 1 or less, in which case the recursion stops.
- The remainder when the number is divided by 2 is printed at each recursive call, resulting in the binary representation.
Approach 5: Bitset
This approach uses the bitset library in C++ to convert the given number to binary by creating a bitset object and using its member functions.
Pros:
- Suitable for any size of numbers, including negative numbers.
- Provides a clean and concise solution using the bitset library.
- Can easily handle different base conversions with minor modifications.
Cons:
- Requires the use of C++ and the bitset library, which may not be available in all C environments.
- May involve additional overhead for including and using the bitset library.
- Requires additional steps to handle negative numbers.
Code:
#include <stdio.h>
void convertToBinary(int num) {
int binary[32]; // Assuming integer is 32 bits
int i = 0;
// Convert integer to binary
while (num > 0) {
binary[i] = num % 2;
num /= 2;
i++;
}
// Print the binary representation
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
printf("\n");
}
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
convertToBinary(num);
return 0;
}
Output:
Input: 10
Output: 1010
Code Explanation:
- The bitset library in C++ provides a convenient way to represent and manipulate binary numbers using bitsets.
- The bitset object is created with the given number as the argument, which automatically converts it to binary representation.
- The to_string() function is used to convert the bitset to a string.
- The binary representation is printed as a string.
Approach 6: String Manipulation
This approach converts the given number to binary by manipulating its bits as strings, using bitwise shifts and string concatenation.
Pros:
- Suitable for any size of numbers, including negative numbers.
- Provides a straightforward approach using string manipulation.
- Can handle different base conversions with minor modifications.
Cons:
- May involve additional overhead for string manipulations.
- Requires additional steps to handle negative numbers.
- May not be as efficient as bitwise approaches for large numbers.
Code:
#include <stdio.h>
void convertToBinary(int num) {
char binary[33]; // Assuming integer is 32 bits, plus null terminator
binary[32] = '\0'; // Null terminate the binary string
for (int i = 31; i >= 0; i--) {
binary[i] = (num & 1) ? '1' : '0'; // Get the least significant bit
num >>= 1; // Right shift the number by 1
}
// Print the binary representation
printf("%s", binary);
}
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("Binary representation: ");
convertToBinary(num);
return 0;
}
Output:
Input: 42
Output: 0000000000000000000000000000101010
Code explanation:
- The binary array is used to collect the bits of the binary representation.
- The loop iterates through each bit of the number from the most significant bit to the least significant bit.
- The least significant bit is obtained using bitwise AND with 1, and ‘1’ or ‘0’ is stored in the binary array accordingly.
- The number is then right shifted by 1 to get the next bit.
- The binary representation is printed as a string.
Best Approach To Convert Number To Binary In C
The qualities of the bitwise shifting approach for converting a number to binary are:
- Efficiency and speed: Bitwise operations are highly efficient and fast, making this approach suitable for large numbers and performance-critical applications.
- Simplicity and ease of understanding: The approach involves simple bitwise shifting and bitwise AND operations, making it easy to understand even for beginners.
- Handling positive integers: This approach works accurately for positive integers, providing an accurate binary representation of the input number.
Overall, the bitwise shifting approach for converting a number to binary is efficient and simple, making it a popular choice in many programming applications.
Sample Problems To Convert Number To Binary In C
Sample Problem 1:
Scenario: A mechanic needs to keep track of the inventory of spare parts in his workshop. He has a total of 8 different types of spare parts, and he wants to represent the quantity of each spare part in binary form for efficient storage and retrieval.
Solution Steps:
- Declare and initialize the integer variable sparePartQty to 15, which represents the total quantity of spare parts.
- Declare an integer array binary with a size of 8 to store the binary representation of sparePartQty.
- Loop through each bit of sparePartQty using bitwise shifting and bitwise AND operation to convert the integer to binary. Store the result in the binary array.
- Print the original quantity of spare parts and the binary representation using printf statements.
Code:
#include <stdio.h>
int main() {
int sparePartQty = 15; // Total quantity of spare parts
int binary[8]; // Array to store binary representation
int i;
printf("Quantity of spare parts: %d\n", sparePartQty);
// Convert the integer to binary using bitwise shifting
for (i = 7; i >= 0; i--) {
binary[i] = sparePartQty & 1;
sparePartQty = sparePartQty >> 1;
}
printf("Binary representation: ");
for (i = 0; i < 8; i++) {
printf("%d", binary[i]);
}
return 0;
}
Output:
Quantity of spare parts: 15
Binary representation: 00001111
Sample Problem 2:
Scenario: A slipper manufacturer wants to optimize the production process by representing the size of slippers using binary numbers. Each slipper size can be represented using 3 bits, with the least significant bit indicating small size (0) or big size (1).
Solution Steps:
- Initialize the slipperSize variable with the desired slipper size value (0-7) and the mask variable with 1 to extract each bit.
- Use a for loop to iterate three times (for three bits in the slipperSize integer) starting from the most significant bit (i = 2) to the least significant bit (i = 0).
- Inside the loop, use bitwise AND operation (&) between slipperSize and mask to extract the current bit, and store the result (1 or 0) in the corresponding element of the binary array.
- Update the mask by shifting it one bit to the left (mask = mask << 1) to extract the next bit in the next iteration. Finally, use another for loop to print the binary representation of slipperSize by iterating through the binary array and printing each element.
Code:
#include <stdio.h>
int main() {
int slipperSize = 5; // Slipper size (0-7)
int mask = 1; // Mask to extract each bit
int binary[3]; // Array to store binary representation
int i;
printf("Slipper size: %d\n", slipperSize);
// Convert the integer to binary using bitwise AND with mask
for (i = 2; i >= 0; i--) {
binary[i] = (slipperSize & mask) ? 1 : 0;
mask = mask << 1;
}
printf("Binary representation: ");
for (i = 0; i < 3; i++) {
printf("%d", binary[i]);
}
return 0;
}
Output:
Slipper size: 5
Binary representation: 101
Sample Problem 3:
Scenario: A laptop manufacturer wants to store the serial numbers of laptops in binary form for efficient tracking and inventory management. Each laptop has a unique serial number that is represented as an integer.
Solution Steps:
- Declare and initialize variables laptopSerialNumber and mask to store the laptop serial number and the mask to extract each bit, respectively. Also, declare an integer array binary to store the binary representation, and an integer variable i for looping.
- Use printf to print the laptop serial number.
- Use a bitwise AND operation with a mask to extract each bit of the laptopSerialNumber. If the result is non-zero, store 1 in the corresponding index of the binary array, otherwise store 0. Update the mask by shifting it one bit to the left in each iteration to extract the next bit, and repeat the process for all 16 bits of the integer.
- Use a for loop and printf to print the binary representation stored in the binary array, which will display the binary digits.
Code:
#include <stdio.h>
int main() {
int laptopSerialNumber = 123; // Laptop serial number
int mask = 1; // Mask to extract each bit
int binary[16]; // Array to store binary representation
int i;
printf("Laptop serial number: %d\n", laptopSerialNumber);
// Convert the integer to binary using bitwise AND with mask
for (i = 15; i >= 0; i--) {
binary[i] = (laptopSerialNumber & mask) ? 1 : 0;
mask = mask << 1;
}
printf("Binary representation: ");
for (i = 0; i < 16; i++) {
printf("%d", binary[i]);
}
return 0;
}
Output:
Laptop serial number: 123
Binary representation: 0000000001111011
Sample Problem 4:
Scenario: A social media platform like Facebook wants to store user profile data in binary form for efficient storage and retrieval. One of the profile data fields is the user’s age, which is represented as an integer.
Solution Steps:
- Define a recursive function convertToBinary that takes an integer num as input.
- Add a base case in the function that checks if num is zero or negative, and if so, return immediately.
- Inside the function, calculate the quotient and remainder of num divided by 2.
- Recursively call the convertToBinary function with the quotient, and then print the remainder as the binary digit using printf function.
Code:
#include <stdio.h>
// Recursive function to convert a number to binary
void convertToBinary(int num) {
// Base case: if num is zero or negative, return
if (num <= 0) {
return;
}
// Get the quotient and remainder
int quotient = num / 2;
int remainder = num % 2;
// Recursively call the function with the quotient
convertToBinary(quotient);
// Print the remainder as the binary digit
printf("%d", remainder);
}
int main() {
int num = 10; // Number to convert to binary
printf("Binary representation of %d: ", num);
convertToBinary(num); // Call the recursive function
printf("\n");
return 0;
}
Output:
Binary representation of 10: 1010
Sample Problem 5:
Scenario: A TV manufacturer wants to represent the screen size of TVs using binary numbers. Each TV has a screen size that ranges from 10 inches to 60 inches, and the TV models are identified using a unique integer ID.
Solution Steps:
- Declare variables for the TV model ID, screen size in inches, and the number of bits required for screen size. Also, declare a boolean array to represent the binary representation of the screen size.
- Use a while loop to convert the screen size into its binary representation. This is done by setting the corresponding bit in the bitset array based on whether the current digit in the binary representation is a 0 or 1.
- Use printf statements to print out the TV model ID, screen size, and the binary representation of the screen size. The binary representation is obtained by calling the printBinary function and passing in the bitset array and the number of bits required for the screen size.
- End the program by returning 0 from the main function.
Code:
#include <stdio.h>
#include <stdbool.h>
void printBinary(bool* bitset, int size) {
for (int i = size - 1; i >= 0; i--) {
printf("%d", bitset[i]);
}
}
int main() {
int tvID = 12345; // TV model ID
int screenSize = 42; // TV screen size in inches
int size = 6; // Number of bits required for screen size (10-60 inches)
bool bitset[6] = {0}; // Bitset to represent the binary representation
int i = 0;
printf("TV ID: %d\n", tvID);
printf("Screen size: %d inches\n", screenSize);
// Set the corresponding bit in the bitset based on the screen size
while (screenSize > 0) {
bitset[i++] = screenSize % 2;
screenSize /= 2;
}
printf("Binary representation: ");
printBinary(bitset, size);
return 0;
}
Output:
TV ID: 12345
Screen size: 42 inches
Binary representation: 010101
Sample Problem 6:
Scenario: A fruit seller wants to represent the quantity of mangoes they have in binary form for efficient storage and retrieval. Each mango quantity is represented as an integer.
Solution Steps:
- The program initializes an integer variable called mangoQuantity and sets it to 35.
- It declares a character array variable called str with a length of 10, which will be used to hold the string representation of the integer value.
- The program converts the integer value of mangoQuantity to a string using the sprintf() function and stores it in the str variable.
- It calls the printBinary() function to print the binary representation of the string value stored in str. This function takes the string as a parameter and converts each character to its binary representation using a nested for loop.
- The program returns 0 to indicate successful execution.
.
Code:
#include <stdio.h>
#include <string.h>
void printBinary(char* str) {
for (int i = 0; i < strlen(str); i++) {
int decimalValue = str[i] - '0'; // Convert character to integer
for (int j = 3; j >= 0; j--) {
printf("%d", (decimalValue >> j) & 1);
}
}
}
int main() {
int mangoQuantity = 35; // Quantity of mangoes
char str[10]; // String to hold the integer value
printf("Mango Quantity: %d\n", mangoQuantity);
// Convert integer to string
sprintf(str, "%d", mangoQuantity);
printf("Binary representation: ");
printBinary(str);
return 0;
}
Output:
Mango Quantity: 35
Binary representation: 00100011
Conclusion
In conclusion, converting a number to binary in C is a fundamental skill for any programmer. Understanding how numbers are represented in binary form is crucial for working with digital systems. In this blog, we have explored the six different techniques whereas bitwise shifting comes up as the best approach. So, by mastering the techniques of converting numbers to binary in C, you can leverage the power of binary representation in your programming projects.