[英]Converting integer to a sizable vector or string
I am converting a decimal integer into a binary without using strings (in Visual Studio 2013): 我将一个十进制整数转换为二进制而不使用字符串(在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.
问题是我想控制二进制输出中的位数,即要0而不是0,或者要01,而不是1。
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? 如何将输出转换为具有适当大小的向量/字符串,以便在转换十进制数字“ 1”时,在返回的输出中可以有“ 001”或“ 0001”,这取决于我需要多少位数?
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.
但这并没有改变我的代码中输出向量“ bin”的长度。 It only prints '000' on the screen.
它仅在屏幕上打印“ 000”。
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 您可以在这里进行测试http://cpp.sh/5cx
Having called your de2bi
function, you can display the result n
as a w
-character wide output as follows: 调用
de2bi
函数后,可以将结果n
显示为w
字符宽的输出,如下所示:
#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
. 例如,如果
w
为3
且n
为1
,则得到001
。
There are many other SO questions and answers with more direct ways to display a number in binary, eg here . 还有许多其他SO问题和答案,以及使用直接方式以二进制形式显示数字的方法,例如here 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.