Home > Back-end >  c conversion from decimal to binary
c conversion from decimal to binary

Time:01-09

i am writing program for conversion of decimal to binary but answer i am getting is not correct i had checked it multiple times but couldn't make it.

`

#include<iostream>
#include<math.h>
using namespace std;
int decitobin(int n){
    int ans=0;
    int i=0;
    while(n!=0){
        int bit=n&1;
        ans=((bit * pow(10,i)) ans);
        n=n>>1;
        i  ;
    }
    return ans;
}  
int main(){
    int n;
    cin>>n;
    if(n<0){
        n=n*(-1);
        int newans=decitobin(n);
        //1stcomp
        newans=(~newans);
        newans=newans 1;
        cout<<newans<<endl;
    }
    else{
        cout<<decitobin(n);
    }

} 

`

i am getting output 100 for 5,99 for 4 and -109 for -6

i had checked each line make it match with the solution but could not figure it out

CodePudding user response:

Note in C there is an easier way (though that probably will not be what your teacher asked for)

#include <bitset>
#include <iostream>

int main()
{
    std::size_t value{ 112ul };
    std::bitset<8> bits{ value };
    std::cout << bits;
    return 0;
}

CodePudding user response:

Another way of doing it in code without even needing base 10 logic. Just to show you numbers in memory are already in binary format. Often in dealing with binary data you will need masks and shift operations.

#include <array>
#include <iostream>

auto get_number_of_bits(int value)
{
    std::size_t n{ 1ul };
    value >>= 1;

    while (value != 0) 
    {
          n;
        value >>= 1;
    }

    return n;
}

// note value will already be a binary number in memory
// we just need to "walk" over all the bits and
// insert a '0' or '1' to the string
std::string to_bin(const int value)
{
    // calculate the number of bits present in the number
    const auto number_of_bits{ get_number_of_bits(value) };

    // allocate a string to hold the correct/minimal number of bits in the output
    std::string string(number_of_bits,0);
    int mask{ 0x01 << (number_of_bits - 1ul) }; // select which bit we want from number

    // loop over the bits
    for (std::size_t n{ 0ul }; n < number_of_bits;   n)
    {
        string[n] = (value & mask) ? '1' : '0'; // test if bit is set if so insert a 1 otherwise a 0
        mask >>= 1;
    }

    return string;
}

int main()
{
    std::cout << to_bin(5) << "\n";
    std::cout << to_bin(12345) << "\n";

    return 0;
}
  • Related