Convert a number into binary format in C,C++
There are multiple approaches to do the same. I am listing three methods known to me.
Here is the code :
Here is the code :
#include <iostream> #include <conio.h> #include <bitset> #include <iomanip> using namespace std; void Method_1(int num) { const std::string result = bitset<sizeof(num)*CHAR_BIT>(num).to_string(); cout << result.substr(result.find("1", 0)); } void Method_2(int num) { if (num / 2 != 0) { Method_2(num / 2); } cout<<num % 2; } void Method_3(int num) { std::string result = ""; for (int i = (sizeof(num)* CHAR_BIT); i >= 0; --i) result += ((num & (1 << i)) ? "1" : "0"); cout << result.substr(result.find("1", 0)); } void main() { int num = 30; cout << "Method 1 : "; Method_1(num); cout << endl; cout << "Method 2 : "; Method_2(num); cout << endl; cout << "Method 3 : "; Method_3(num); cout << endl; _getch(); }Thanks for Visiting.
Comments
Post a Comment