简体   繁体   English

c++ 十进制转二进制

[英]c++ conversion from decimal to binary

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我得到 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我检查了每一行使其与解决方案匹配但无法弄清楚

Note in C++ there is an easier way (though that probably will not be what your teacher asked for)请注意 C++ 中有一个更简单的方法(尽管这可能不是您的老师所要求的)

#include <bitset>
#include <iostream>

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

Another way of doing it in code without even needing base 10 logic.另一种在代码中执行此操作的方法甚至不需要以 10 为基数的逻辑。 Just to show you numbers in memory are already in binary format.只是为了向您展示 memory 中的数字已经是二进制格式。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM