Print binary representation of a number – C, C++, Java, and Python
Print binary representation of a given number in C, C++, Java, and Python using built-in methods and custom routines.
For example,
Output: 00000000000000000000000000010100
Input: 64
Output: 00000000000000000000000001000000
Input: 127
Output: 00000000000000000000000001111111
Input: -1
Output: 11111111111111111111111111111111
1. Iterative Solution
The idea is to check if i'th bit is set for each position i in the given integer n. If i'th bit is set for position i in integer n, then set i'th bit to 1 in the binary representation of n; otherwise, 0. The i ranges from 0 to 31 for a 32–bit integer.
The expression 1 << (i - 1) gives a number that has only i'th bit set. If we do bitwise AND of this expression with any number n, i.e., n & (1 << (i - 1)), a non-zero value indicates that its i'th bit is set for number n. For instance, consider n = 20 and i = 3. The result is a non-zero value, which indicates that the 3rd bit is set for integer 20.
00000100 (1 << (3-1))
~~~~~~~~
00000100 non-zero value
The time complexity of this solution is O(c), and no extra space is used. Here, c indicates a constant value. Following is the implementation in C, Java, and Python based on the above idea:
C
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <stdio.h> #include <stdlib.h> char* toBinary(int n, int len) { char* binary = (char*)malloc(sizeof(char) * len); int k = 0; for (unsigned i = (1 << len - 1); i > 0; i = i / 2) { binary[k++] = (n & i) ? '1' : '0'; } binary[k] = '\0'; return binary; } int main(void) { int n = 20; int len = 32; char* binary = toBinary(n, len); printf("The binary representation of %d is %s", n, binary); free(binary); return 0; } |
C++
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <string> using namespace std; string toBinary(int n, int len) { string binary; for (unsigned i = (1 << len - 1); i > 0; i = i / 2) { binary += (n & i) ? "1" : "0"; } return binary; } int main() { int n = 20; int len = 32; cout << "The binary representation of " << n << " is " << toBinary(n, len); return 0; } |
Java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Main { public static String toBinary(int n, int len) { String binary = ""; for (long i = (1L << len - 1); i > 0; i = i / 2) { binary += (n & i) != 0 ? "1" : "0"; } return binary; } public static void main(String[] args) { int n = 20; int len = 32; String binary = toBinary(n, len); System.out.println("The binary representation of " + n + " is " + binary); } } |
Python
The binary representation of 20 is 00000000000000000000000000010100
2. Recursive Solution
For a given number n, the idea is to recur with the value n/2 and add the remainder of n with 2 (n % 2) to the output string. Terminate the recursion when n becomes 0 and return the output string.
The solution runs in O(log(n)) time and requires O(log(n)) extra space for the call stack. The recurrence relation is T(n) = T(n/2) + 1. However, this works only with positive integers. Following is the C++, Java, and Python program that demonstrates the recursive version:
C++
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <string> using namespace std; string toBinary(unsigned n) { if (n == 0) { return ""; } return toBinary(n / 2) + to_string(n % 2); } int main() { int n = 20; cout << "The binary representation of " << n << " is " << toBinary(n) << endl; return 0; } |
Java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Main { public static String toBinary(int n) { if (n == 0) { return ""; } return toBinary(n / 2) + (n % 2); } public static void main(String[] args) { int n = 20; System.out.println("The binary representation of " + n + " is " + toBinary(n)); } } |
Python
The binary representation of 20 is 10100
3. Using Built-in methods
In C++, we can use the bitset() member function from the std::bitset namespace, which can construct a bitset container object from the integer argument.
In Java, we can use the Integer.toBinaryString() method, which returns the specified integer's string representation.
In Python, we can use the built-in function bin() to convert an integer to a binary string prefixed with 0b. If prefix 0b is not desired, consider using either format() function or f–strings. The f–strings are available in Python starting with v3.6.
C++
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <bitset> using namespace std; bitset<8> toBinary(int n) { return bitset<8>(n); } int main() { int n = 20; cout << "The binary representation of " << n << " is " << toBinary(n) << endl; return 0; } |
Output:
The binary representation of 20 is 00010100
Java
|
1 2 3 4 5 6 7 8 9 10 |
class Main { public static void main(String[] args) { int n = 20; String binary = Integer.toBinaryString(n); System.out.println("The binary representation of " + n + " is " + binary); } } |
Output:
The binary representation of 20 is 10100
Python
|
1 2 3 4 5 6 7 8 9 10 11 |
if __name__ == '__main__': n = 20 print(f"The binary representation of {n} using built-in function bin():", bin(n)) print("Using format() function | With prefix '0b':", format(n, '#b'), "|", "Without prefix '0b':", format(n, 'b')); print(f"Using f–string function | With prefix '0b': {n:#b} | " f"Without prefix '0b': {n:b}") |
Output:
The binary representation of 20 using built-in function bin(): 0b10100
Using format() function | With prefix '0b': 0b10100 | Without prefix '0b': 10100
Using f–string function | With prefix '0b': 0b10100 | Without prefix '0b': 10100
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)