Home > Mobile >  Binary number function
Binary number function

Time:10-11

#include <iostream>
using namespace std;
void binary(unsigned  a) {
    int i;
    cout << "0" << endl;
    do {
        for (i = 1; i < a; i=i/2) {
            if ((a & i) != 0) {
                cout << "1" << endl;
            }
            else {
                cout << "0" << endl;
            
            }
    
        }
    }
    while (1 <= a && a <= 10);
}

int main(void) {
    binary(4);
    cout << endl;
}

I wrote a code about binary numbers. İt should give bits respect to entering number like for 4 (0100) for 2 (10). However my code goes infinity could you explain. I wrote in visual studio and I cannot use <bits/stdc .h> because there is no such a library in visual studio

CodePudding user response:

Initially i is 1 but i = i / 2 sets i to 0, where it remains. The inner loop, therfore, loops for ever.

To output an unsigned number a in binary, use

#include <bitset>
#include <climits>
std::cout << std::bitset<sizeof(a) * CHAR_BIT>(a) << '\n';

(There is, at the time of writing no std::bin i/o manipulator cf. std::hex.)

CodePudding user response:

Without using a built-in function, you can write your own function and perform your operation as follows.

Solution-1

#include <iostream>
void binary(unsigned int number)
{
    if (number / 2 != 0) {
        binary(number / 2);
    }
    std::cout << number % 2;
}

int main() {
    binary(10);
}

Solution-2

#include <iostream>
#include<string>

void binary(unsigned int number)
{
    std::string str = "";
    while (number != 0) { 
        str = (number % 2 == 0 ? "0" : "1")   str;
        number /= 2; 
    }
    std::cout << str;
}
int main()
{
   binary(4);
}

Note : Don't use using namespace std; . Why is "using namespace std;" considered bad practice?

  • Related