简体   繁体   中英

Converting integer to a sizable vector or string

I am converting a decimal integer into a binary without using strings (in Visual Studio 2013):

int de2bi(int de)
{
int bi = 0, pos = 1;
while(de > 0)
{
    bi = bi + (de % 2) * pos;
    de = de / 2;
    pos *= 10;
}
return bin;
}

This way, the binary representation in output is actually a decimal number. The problem is that I want to control the number of digits in my binary output ie instead of 0 I want 00 or instead of 1 I want 01.

How can I convert the output into a vector/string with an appropriate size so that when converting decimal number '1', I can have '001' or '0001' in the returned output, depending on how many digits I need in my output?

Edit: I adopted the code from the answer down below. But it did not change the length of the output vector 'bin' in my code. It only prints '000' on the screen.

std::cout<<std::setw(3)<<std::setfill('0')<<bin;    
std::string de2bi(int de){
    std::string bin = "";
    if( de == 0 ){
        return "0";
    }
    else if( de < 0 ){
        return "";
    }

    while(de){
        bin = std::to_string(de % 2) + bin ;
        de = de / 2;
    }
    return bin; 
}

you can test at here http://cpp.sh/5cx

Having called your de2bi function, you can display the result n as a w -character wide output as follows:

#include <iomanip>

std::cout << std::setw(w) << std::setfill('0') << n;

For example, if w is 3 and n is 1 you'll get 001 .

There are many other SO questions and answers with more direct ways to display a number in binary, eg here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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