Autofilling a variable in C++
Sep 28, 2021 at 11:16am UTC
Hi!
I want to learn c++ and want to use binary numbers for my project. From Decimal to binary translation I have already a function, with ceros I want auto fill with 8 characters.
Example: 10 in decimal is converted as 1010, but I want it to be 00001010.
Set fill tool is not operating as I require the digit to be 8 numbers long for using it in other function.
Will any one help me? The code is here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include <iostream>
#include <cmath>
using namespace std;
int binario(int n);
int main(int argc, char *argv[]) {
int n;
cin>>n;
int binn=binario(n);
cout<<binn;
return 0;
}
int binario(int n){
int exp, digito;
double binarion;
exp=0;
binarion=0;
while (n/2!=0&&exp<8)
{
digito = n % 2;
binarion = binarion + digito * pow(10.0,exp);
exp++;
n=n/2;
}
binarion = binarion + n * pow(10.0,exp);
return binarion;
Thanks.
Last edited on Sep 28, 2021 at 11:18am UTC
Sep 28, 2021 at 11:20am UTC
Use a std::string to contain your binary number, not an int.
Sep 28, 2021 at 12:03pm UTC
Based upon the OP algorithm, perhaps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <iomanip>
#include <cmath>
int binario(int n) {
int exp {}, binarion {};
for (; n / 2 != 0 && exp < 8; n /= 2)
binarion += (n % 2) * static_cast <int >(pow(10.0, exp++));
return binarion + n * static_cast <int >(pow(10.0, exp));
}
int main() {
int n {};
std::cin >> n;
std::cout << std::setw(8) << std::setfill('0' ) << binario(n) << '\n' ;
}
Sep 28, 2021 at 1:36pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
#include <string>
using namespace std;
string binario( unsigned n );
int main()
{
unsigned n;
cout << "Enter an integer: " ;
cin >> n;
cout << binario( n );
}
string binario( unsigned n )
{
const int LENGTH = 8;
string result;
while ( n && result.size() < LENGTH )
{
result = "01" [n%2] + result;
n /= 2;
}
return string( LENGTH - result.size(), '0' ) + result;
}
Actually, the following works quite well, too:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <string>
#include <bitset>
using namespace std;
string binario( unsigned n );
int main()
{
unsigned n;
cout << "Enter an integer: " ;
cin >> n;
cout << binario( n );
}
string binario( unsigned n )
{
return bitset<8>( n ).to_string();
}
Last edited on Sep 28, 2021 at 1:44pm UTC
Topic archived. No new replies allowed.