how do I improve: The number to binary code C++
-
#include
#include
using namespace std;void line() { cout << setw(12) << setfill('-') << endl;}
int main() {
int binary[8];
int num;
int bits[8] = {128,64,32,16,8,4,2,1};do {
line();
cout << "write in the number to be converted into binary." << endl;
cin >> num;for(int i = 0;i < 8;i++) {
if(num >= bits[i]){
binary[i] = true;
num = num - bits[i];}
else if(num < bits[i]) {
binary[i] = false;
}}
for(int i = 0;i < 8;i++) {
cout << binary[i] ;
}
}while (1);system("pause");
return 0;
}this code is made about 1 month ago,and this is supposed to convert numbers into binary. Since I'm a beginner,the code might be messy and unintelligent. Please tell me how to improve this or to make it more efficient. If by any chance I'm in the wrong section, forgive me,this is the first time visiting this site.
-
#include
#include
using namespace std;void line() { cout << setw(12) << setfill('-') << endl;}
int main() {
int binary[8];
int num;
int bits[8] = {128,64,32,16,8,4,2,1};do {
line();
cout << "write in the number to be converted into binary." << endl;
cin >> num;for(int i = 0;i < 8;i++) {
if(num >= bits[i]){
binary[i] = true;
num = num - bits[i];}
else if(num < bits[i]) {
binary[i] = false;
}}
for(int i = 0;i < 8;i++) {
cout << binary[i] ;
}
}while (1);system("pause");
return 0;
}this code is made about 1 month ago,and this is supposed to convert numbers into binary. Since I'm a beginner,the code might be messy and unintelligent. Please tell me how to improve this or to make it more efficient. If by any chance I'm in the wrong section, forgive me,this is the first time visiting this site.
It is the wrong forum - you want either Quick Answers[^] or tHE c++ Forum[^] However, that is a bit of an odd way to do it. I would have a single loop and a single test:
for (int i = 0; i < 8; i++)
{
cout << (num & 0x80) != 0 ? "1" : "0";
num <<= 1;
}Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water
-
It is the wrong forum - you want either Quick Answers[^] or tHE c++ Forum[^] However, that is a bit of an odd way to do it. I would have a single loop and a single test:
for (int i = 0; i < 8; i++)
{
cout << (num & 0x80) != 0 ? "1" : "0";
num <<= 1;
}Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water
Or (untested):
for(int i = 0x80; i > 0; i >>= 1)
{
cout << (num & i) ? "1" : "0";
}Dunno if the code spared is worth it, though.