Program that outputs binary values of inputBit-twiddling for a custom image formatNecklace counting problem-with consecutive prime constraintUgly_Numbers challengeAddition of two IEEE754-32bit single precision floating point numbers in C++Given two strings, a and b, determine the minimum number of character deletions required to make a and b anagramsCalculating the Riemann Zeta Function for x>2 real numbersAdvent of Code 2017, Day 1: Sum of digits matching the next digit (circular list)Sieve of Eratosthenes for small limitsFinding intersting path in a graphSimple Binary to Decimal Converter

Why are there 40 737 Max planes in flight when they have been grounded as not airworthy?

What is the greatest age difference between a married couple in Tanach?

Define, (actually define) the "stability" and "energy" of a compound

Be in awe of my brilliance!

Why did it take so long to abandon sail after steamships were demonstrated?

PlotLabels with equations not expressions

What is IP squat space

How to answer questions about my characters?

Dot in front of file

Should we release the security issues we found in our product as CVE or we can just update those on weekly release notes?

Meaning of "SEVERA INDEOVI VAS" from 3rd Century slab

Professor being mistaken for a grad student

How can I change step-down my variable input voltage? [Microcontroller]

Current sense amp + op-amp buffer + ADC: Measuring down to 0 with single supply

PTIJ: Who should pay for Uber rides: the child or the parent?

What options are left, if Britain cannot decide?

Bash: What does "masking return values" mean?

What does it mean to make a bootable LiveUSB?

When do we add an hyphen (-) to a complex adjective word?

Why doesn't the EU now just force the UK to choose between referendum and no-deal?

Is it possible to upcast ritual spells?

Is having access to past exams cheating and, if yes, could it be proven just by a good grade?

Making a sword in the stone, in a medieval world without magic

Rules about breaking the rules. How do I do it well?



Program that outputs binary values of input


Bit-twiddling for a custom image formatNecklace counting problem-with consecutive prime constraintUgly_Numbers challengeAddition of two IEEE754-32bit single precision floating point numbers in C++Given two strings, a and b, determine the minimum number of character deletions required to make a and b anagramsCalculating the Riemann Zeta Function for x>2 real numbersAdvent of Code 2017, Day 1: Sum of digits matching the next digit (circular list)Sieve of Eratosthenes for small limitsFinding intersting path in a graphSimple Binary to Decimal Converter













2












$begingroup$


I am looking to simplify my main() function. The nested if statements contain four lines of the same code, and I'm unsure of how to refactor and simplify it. I was attempting to use booleans, which seemed like a safe bet, but the logic gets skewed in the process.



#include <bits/stdc++.h>
#include <iostream>
#include <string>

int bits(unsigned long d)
int l;

if (d <= 255)
l = 8;

else if (d > 255 && d <= 65535)
l = 16;

else if (d > 65535 && d <= 4294967295U)
l = 32;

else
std::cout << "32 bits (4294967295) or smaller." << std::endl;


std::cout << "Bits..................... " << l << std::endl;

return l;


std::string convertToBinary(unsigned long decimal)
int l = bits(decimal);
int i, r;
std::string str;

// creates array
for (i = 0; i < l; i++)
r = decimal % 2;
decimal /= 2;
str += std::to_string(r);


// reverses array for binary value
reverse(str.begin(), str.end());

std::cout << "Binary Value............. " << str << std::endl;

return str;


int main(void)
std::string input;
std::cout << "------------ Input -----------" << std::endl;
std::cin >> input;

std::cout << "Input: " << input << std::endl;
std::cout << "Length: " << input.length() << std::endl;

int i, count = 0, j = 0;
int length = input.length();
int ascii;
unsigned long nums;

int numbers[33];
std::string binaries;
std::string chars;

for (i = 0; i < length; i++)
// if next input is digit
if (isdigit(input[i]))
numbers[j] = input[i];
// place digit in next decimal
count = (numbers[j] - '0') + count * 10;
// if next input is char
if (i == length - 1)
if (isdigit(input[length - 1]))
nums = count;
std::cout << "------------ " << nums << " ------------" << std::endl;
binaries += convertToBinary(nums) + ' ';
count = 0;


// next number
j++;

// if next input is char
else
chars[i] = input[i];
ascii = (int) chars[i];
// if next input is digit
if (count != 0)
nums = count;
std::cout << "------------ " << nums << " ------------" << std::endl;
binaries += convertToBinary(nums) + ' ';
count = 0;

// != end of letters
std::cout << "------------ " << chars[i] << " ------------" << std::endl;
std::cout << "ASCII.................... " << ascii << std::endl;
binaries += convertToBinary(ascii) + ' ';



std::cout << "n------- Binary Value of " << input << " -------" << std::endl;
std::cout << binaries << std::endl;

return 0;



The program takes an input, then outputs the corresponding number of bits, binary value, and if necessary, an ASCII value. If the user inputs "c357g98", then the program should get ASCII and binary values of "c", then retrieve the binary value of "357" (rather than "3", "5", then "7" individually), so any adjacent digits will be treated as a single int instead of separate integers. Each time I attempt to refactor, the program loses its ability to store the adjacent digits together as a single int.



In the first attempt at refactoring, I tried this, which takes the count and binary parameters:



void getNumbers(int c, std::string b) 
std::cout << "------------ " << c << " ------------" << std::endl;
b += convertToBinary(c) + ' ';
c = 0;



Since the count is never returned, the input "c357g98" is treated as "c357g35798" and the numbers never reset.



So in my second attempt, I return the count variable as an int:



int getNumbers(int c, std::string b) 
std::cout << "------------ " << c << " ------------" << std::endl;
b += convertToBinary(c) + ' ';
c = 0;

return c;



And replace the four lines of code with a reference to the function as:



count = getNumbers(count, binaries);


This method converts each value correctly, but does not store the final binary values of the digits, only the characters (since the reference to the string binaries was moved and not returned).



I've also done away with the nums variable entirely.



I'm coming to terms with the idea that my entire program may need heavily refactored in order for the logic to be simplified, but I was hoping to start with the messy main() function for now.










share|improve this question









New contributor




J Pex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$











  • $begingroup$
    What have you attempted to do to refactor it? Assuming the four lines you are referring to are the ones beginning with nums = count;, why can't you put those four lines in a function that accepts references to nums and count?
    $endgroup$
    – Null
    8 hours ago










  • $begingroup$
    @Null I created a function that takes count and binaries, then returns the count. So the four lines are then replaced with count = getNumbers(count, binaries); This method will skip the digits entirely, and when the program is due to print all final binary values at the end, only the characters are converted. In my second attempt, I changed the function to string getNumbers and had the binaries string be returned instead, and the four lines of code in the nested ifstatements were replaced with binaries += getNumbers(count, binaries); This method does not reset the counter.
    $endgroup$
    – J Pex
    8 hours ago










  • $begingroup$
    It's hard to follow that in a comment. Please edit your question with the attempted refactor code.
    $endgroup$
    – Null
    8 hours ago










  • $begingroup$
    @Null I apologize, I was unaware of the correct protocol for editing posts. I've edited the post now to include my attempts.
    $endgroup$
    – J Pex
    7 hours ago















2












$begingroup$


I am looking to simplify my main() function. The nested if statements contain four lines of the same code, and I'm unsure of how to refactor and simplify it. I was attempting to use booleans, which seemed like a safe bet, but the logic gets skewed in the process.



#include <bits/stdc++.h>
#include <iostream>
#include <string>

int bits(unsigned long d)
int l;

if (d <= 255)
l = 8;

else if (d > 255 && d <= 65535)
l = 16;

else if (d > 65535 && d <= 4294967295U)
l = 32;

else
std::cout << "32 bits (4294967295) or smaller." << std::endl;


std::cout << "Bits..................... " << l << std::endl;

return l;


std::string convertToBinary(unsigned long decimal)
int l = bits(decimal);
int i, r;
std::string str;

// creates array
for (i = 0; i < l; i++)
r = decimal % 2;
decimal /= 2;
str += std::to_string(r);


// reverses array for binary value
reverse(str.begin(), str.end());

std::cout << "Binary Value............. " << str << std::endl;

return str;


int main(void)
std::string input;
std::cout << "------------ Input -----------" << std::endl;
std::cin >> input;

std::cout << "Input: " << input << std::endl;
std::cout << "Length: " << input.length() << std::endl;

int i, count = 0, j = 0;
int length = input.length();
int ascii;
unsigned long nums;

int numbers[33];
std::string binaries;
std::string chars;

for (i = 0; i < length; i++)
// if next input is digit
if (isdigit(input[i]))
numbers[j] = input[i];
// place digit in next decimal
count = (numbers[j] - '0') + count * 10;
// if next input is char
if (i == length - 1)
if (isdigit(input[length - 1]))
nums = count;
std::cout << "------------ " << nums << " ------------" << std::endl;
binaries += convertToBinary(nums) + ' ';
count = 0;


// next number
j++;

// if next input is char
else
chars[i] = input[i];
ascii = (int) chars[i];
// if next input is digit
if (count != 0)
nums = count;
std::cout << "------------ " << nums << " ------------" << std::endl;
binaries += convertToBinary(nums) + ' ';
count = 0;

// != end of letters
std::cout << "------------ " << chars[i] << " ------------" << std::endl;
std::cout << "ASCII.................... " << ascii << std::endl;
binaries += convertToBinary(ascii) + ' ';



std::cout << "n------- Binary Value of " << input << " -------" << std::endl;
std::cout << binaries << std::endl;

return 0;



The program takes an input, then outputs the corresponding number of bits, binary value, and if necessary, an ASCII value. If the user inputs "c357g98", then the program should get ASCII and binary values of "c", then retrieve the binary value of "357" (rather than "3", "5", then "7" individually), so any adjacent digits will be treated as a single int instead of separate integers. Each time I attempt to refactor, the program loses its ability to store the adjacent digits together as a single int.



In the first attempt at refactoring, I tried this, which takes the count and binary parameters:



void getNumbers(int c, std::string b) 
std::cout << "------------ " << c << " ------------" << std::endl;
b += convertToBinary(c) + ' ';
c = 0;



Since the count is never returned, the input "c357g98" is treated as "c357g35798" and the numbers never reset.



So in my second attempt, I return the count variable as an int:



int getNumbers(int c, std::string b) 
std::cout << "------------ " << c << " ------------" << std::endl;
b += convertToBinary(c) + ' ';
c = 0;

return c;



And replace the four lines of code with a reference to the function as:



count = getNumbers(count, binaries);


This method converts each value correctly, but does not store the final binary values of the digits, only the characters (since the reference to the string binaries was moved and not returned).



I've also done away with the nums variable entirely.



I'm coming to terms with the idea that my entire program may need heavily refactored in order for the logic to be simplified, but I was hoping to start with the messy main() function for now.










share|improve this question









New contributor




J Pex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$











  • $begingroup$
    What have you attempted to do to refactor it? Assuming the four lines you are referring to are the ones beginning with nums = count;, why can't you put those four lines in a function that accepts references to nums and count?
    $endgroup$
    – Null
    8 hours ago










  • $begingroup$
    @Null I created a function that takes count and binaries, then returns the count. So the four lines are then replaced with count = getNumbers(count, binaries); This method will skip the digits entirely, and when the program is due to print all final binary values at the end, only the characters are converted. In my second attempt, I changed the function to string getNumbers and had the binaries string be returned instead, and the four lines of code in the nested ifstatements were replaced with binaries += getNumbers(count, binaries); This method does not reset the counter.
    $endgroup$
    – J Pex
    8 hours ago










  • $begingroup$
    It's hard to follow that in a comment. Please edit your question with the attempted refactor code.
    $endgroup$
    – Null
    8 hours ago










  • $begingroup$
    @Null I apologize, I was unaware of the correct protocol for editing posts. I've edited the post now to include my attempts.
    $endgroup$
    – J Pex
    7 hours ago













2












2








2





$begingroup$


I am looking to simplify my main() function. The nested if statements contain four lines of the same code, and I'm unsure of how to refactor and simplify it. I was attempting to use booleans, which seemed like a safe bet, but the logic gets skewed in the process.



#include <bits/stdc++.h>
#include <iostream>
#include <string>

int bits(unsigned long d)
int l;

if (d <= 255)
l = 8;

else if (d > 255 && d <= 65535)
l = 16;

else if (d > 65535 && d <= 4294967295U)
l = 32;

else
std::cout << "32 bits (4294967295) or smaller." << std::endl;


std::cout << "Bits..................... " << l << std::endl;

return l;


std::string convertToBinary(unsigned long decimal)
int l = bits(decimal);
int i, r;
std::string str;

// creates array
for (i = 0; i < l; i++)
r = decimal % 2;
decimal /= 2;
str += std::to_string(r);


// reverses array for binary value
reverse(str.begin(), str.end());

std::cout << "Binary Value............. " << str << std::endl;

return str;


int main(void)
std::string input;
std::cout << "------------ Input -----------" << std::endl;
std::cin >> input;

std::cout << "Input: " << input << std::endl;
std::cout << "Length: " << input.length() << std::endl;

int i, count = 0, j = 0;
int length = input.length();
int ascii;
unsigned long nums;

int numbers[33];
std::string binaries;
std::string chars;

for (i = 0; i < length; i++)
// if next input is digit
if (isdigit(input[i]))
numbers[j] = input[i];
// place digit in next decimal
count = (numbers[j] - '0') + count * 10;
// if next input is char
if (i == length - 1)
if (isdigit(input[length - 1]))
nums = count;
std::cout << "------------ " << nums << " ------------" << std::endl;
binaries += convertToBinary(nums) + ' ';
count = 0;


// next number
j++;

// if next input is char
else
chars[i] = input[i];
ascii = (int) chars[i];
// if next input is digit
if (count != 0)
nums = count;
std::cout << "------------ " << nums << " ------------" << std::endl;
binaries += convertToBinary(nums) + ' ';
count = 0;

// != end of letters
std::cout << "------------ " << chars[i] << " ------------" << std::endl;
std::cout << "ASCII.................... " << ascii << std::endl;
binaries += convertToBinary(ascii) + ' ';



std::cout << "n------- Binary Value of " << input << " -------" << std::endl;
std::cout << binaries << std::endl;

return 0;



The program takes an input, then outputs the corresponding number of bits, binary value, and if necessary, an ASCII value. If the user inputs "c357g98", then the program should get ASCII and binary values of "c", then retrieve the binary value of "357" (rather than "3", "5", then "7" individually), so any adjacent digits will be treated as a single int instead of separate integers. Each time I attempt to refactor, the program loses its ability to store the adjacent digits together as a single int.



In the first attempt at refactoring, I tried this, which takes the count and binary parameters:



void getNumbers(int c, std::string b) 
std::cout << "------------ " << c << " ------------" << std::endl;
b += convertToBinary(c) + ' ';
c = 0;



Since the count is never returned, the input "c357g98" is treated as "c357g35798" and the numbers never reset.



So in my second attempt, I return the count variable as an int:



int getNumbers(int c, std::string b) 
std::cout << "------------ " << c << " ------------" << std::endl;
b += convertToBinary(c) + ' ';
c = 0;

return c;



And replace the four lines of code with a reference to the function as:



count = getNumbers(count, binaries);


This method converts each value correctly, but does not store the final binary values of the digits, only the characters (since the reference to the string binaries was moved and not returned).



I've also done away with the nums variable entirely.



I'm coming to terms with the idea that my entire program may need heavily refactored in order for the logic to be simplified, but I was hoping to start with the messy main() function for now.










share|improve this question









New contributor




J Pex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




I am looking to simplify my main() function. The nested if statements contain four lines of the same code, and I'm unsure of how to refactor and simplify it. I was attempting to use booleans, which seemed like a safe bet, but the logic gets skewed in the process.



#include <bits/stdc++.h>
#include <iostream>
#include <string>

int bits(unsigned long d)
int l;

if (d <= 255)
l = 8;

else if (d > 255 && d <= 65535)
l = 16;

else if (d > 65535 && d <= 4294967295U)
l = 32;

else
std::cout << "32 bits (4294967295) or smaller." << std::endl;


std::cout << "Bits..................... " << l << std::endl;

return l;


std::string convertToBinary(unsigned long decimal)
int l = bits(decimal);
int i, r;
std::string str;

// creates array
for (i = 0; i < l; i++)
r = decimal % 2;
decimal /= 2;
str += std::to_string(r);


// reverses array for binary value
reverse(str.begin(), str.end());

std::cout << "Binary Value............. " << str << std::endl;

return str;


int main(void)
std::string input;
std::cout << "------------ Input -----------" << std::endl;
std::cin >> input;

std::cout << "Input: " << input << std::endl;
std::cout << "Length: " << input.length() << std::endl;

int i, count = 0, j = 0;
int length = input.length();
int ascii;
unsigned long nums;

int numbers[33];
std::string binaries;
std::string chars;

for (i = 0; i < length; i++)
// if next input is digit
if (isdigit(input[i]))
numbers[j] = input[i];
// place digit in next decimal
count = (numbers[j] - '0') + count * 10;
// if next input is char
if (i == length - 1)
if (isdigit(input[length - 1]))
nums = count;
std::cout << "------------ " << nums << " ------------" << std::endl;
binaries += convertToBinary(nums) + ' ';
count = 0;


// next number
j++;

// if next input is char
else
chars[i] = input[i];
ascii = (int) chars[i];
// if next input is digit
if (count != 0)
nums = count;
std::cout << "------------ " << nums << " ------------" << std::endl;
binaries += convertToBinary(nums) + ' ';
count = 0;

// != end of letters
std::cout << "------------ " << chars[i] << " ------------" << std::endl;
std::cout << "ASCII.................... " << ascii << std::endl;
binaries += convertToBinary(ascii) + ' ';



std::cout << "n------- Binary Value of " << input << " -------" << std::endl;
std::cout << binaries << std::endl;

return 0;



The program takes an input, then outputs the corresponding number of bits, binary value, and if necessary, an ASCII value. If the user inputs "c357g98", then the program should get ASCII and binary values of "c", then retrieve the binary value of "357" (rather than "3", "5", then "7" individually), so any adjacent digits will be treated as a single int instead of separate integers. Each time I attempt to refactor, the program loses its ability to store the adjacent digits together as a single int.



In the first attempt at refactoring, I tried this, which takes the count and binary parameters:



void getNumbers(int c, std::string b) 
std::cout << "------------ " << c << " ------------" << std::endl;
b += convertToBinary(c) + ' ';
c = 0;



Since the count is never returned, the input "c357g98" is treated as "c357g35798" and the numbers never reset.



So in my second attempt, I return the count variable as an int:



int getNumbers(int c, std::string b) 
std::cout << "------------ " << c << " ------------" << std::endl;
b += convertToBinary(c) + ' ';
c = 0;

return c;



And replace the four lines of code with a reference to the function as:



count = getNumbers(count, binaries);


This method converts each value correctly, but does not store the final binary values of the digits, only the characters (since the reference to the string binaries was moved and not returned).



I've also done away with the nums variable entirely.



I'm coming to terms with the idea that my entire program may need heavily refactored in order for the logic to be simplified, but I was hoping to start with the messy main() function for now.







c++ c++11 number-systems






share|improve this question









New contributor




J Pex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




J Pex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 4 mins ago









200_success

130k17153419




130k17153419






New contributor




J Pex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 8 hours ago









J PexJ Pex

113




113




New contributor




J Pex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





J Pex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






J Pex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











  • $begingroup$
    What have you attempted to do to refactor it? Assuming the four lines you are referring to are the ones beginning with nums = count;, why can't you put those four lines in a function that accepts references to nums and count?
    $endgroup$
    – Null
    8 hours ago










  • $begingroup$
    @Null I created a function that takes count and binaries, then returns the count. So the four lines are then replaced with count = getNumbers(count, binaries); This method will skip the digits entirely, and when the program is due to print all final binary values at the end, only the characters are converted. In my second attempt, I changed the function to string getNumbers and had the binaries string be returned instead, and the four lines of code in the nested ifstatements were replaced with binaries += getNumbers(count, binaries); This method does not reset the counter.
    $endgroup$
    – J Pex
    8 hours ago










  • $begingroup$
    It's hard to follow that in a comment. Please edit your question with the attempted refactor code.
    $endgroup$
    – Null
    8 hours ago










  • $begingroup$
    @Null I apologize, I was unaware of the correct protocol for editing posts. I've edited the post now to include my attempts.
    $endgroup$
    – J Pex
    7 hours ago
















  • $begingroup$
    What have you attempted to do to refactor it? Assuming the four lines you are referring to are the ones beginning with nums = count;, why can't you put those four lines in a function that accepts references to nums and count?
    $endgroup$
    – Null
    8 hours ago










  • $begingroup$
    @Null I created a function that takes count and binaries, then returns the count. So the four lines are then replaced with count = getNumbers(count, binaries); This method will skip the digits entirely, and when the program is due to print all final binary values at the end, only the characters are converted. In my second attempt, I changed the function to string getNumbers and had the binaries string be returned instead, and the four lines of code in the nested ifstatements were replaced with binaries += getNumbers(count, binaries); This method does not reset the counter.
    $endgroup$
    – J Pex
    8 hours ago










  • $begingroup$
    It's hard to follow that in a comment. Please edit your question with the attempted refactor code.
    $endgroup$
    – Null
    8 hours ago










  • $begingroup$
    @Null I apologize, I was unaware of the correct protocol for editing posts. I've edited the post now to include my attempts.
    $endgroup$
    – J Pex
    7 hours ago















$begingroup$
What have you attempted to do to refactor it? Assuming the four lines you are referring to are the ones beginning with nums = count;, why can't you put those four lines in a function that accepts references to nums and count?
$endgroup$
– Null
8 hours ago




$begingroup$
What have you attempted to do to refactor it? Assuming the four lines you are referring to are the ones beginning with nums = count;, why can't you put those four lines in a function that accepts references to nums and count?
$endgroup$
– Null
8 hours ago












$begingroup$
@Null I created a function that takes count and binaries, then returns the count. So the four lines are then replaced with count = getNumbers(count, binaries); This method will skip the digits entirely, and when the program is due to print all final binary values at the end, only the characters are converted. In my second attempt, I changed the function to string getNumbers and had the binaries string be returned instead, and the four lines of code in the nested ifstatements were replaced with binaries += getNumbers(count, binaries); This method does not reset the counter.
$endgroup$
– J Pex
8 hours ago




$begingroup$
@Null I created a function that takes count and binaries, then returns the count. So the four lines are then replaced with count = getNumbers(count, binaries); This method will skip the digits entirely, and when the program is due to print all final binary values at the end, only the characters are converted. In my second attempt, I changed the function to string getNumbers and had the binaries string be returned instead, and the four lines of code in the nested ifstatements were replaced with binaries += getNumbers(count, binaries); This method does not reset the counter.
$endgroup$
– J Pex
8 hours ago












$begingroup$
It's hard to follow that in a comment. Please edit your question with the attempted refactor code.
$endgroup$
– Null
8 hours ago




$begingroup$
It's hard to follow that in a comment. Please edit your question with the attempted refactor code.
$endgroup$
– Null
8 hours ago












$begingroup$
@Null I apologize, I was unaware of the correct protocol for editing posts. I've edited the post now to include my attempts.
$endgroup$
– J Pex
7 hours ago




$begingroup$
@Null I apologize, I was unaware of the correct protocol for editing posts. I've edited the post now to include my attempts.
$endgroup$
– J Pex
7 hours ago










1 Answer
1






active

oldest

votes


















0












$begingroup$

The first 3 lines in main can be turned into a function:



std::string getInput()

std::string input;
std::cout << "------------ Input -----------" << std::endl;
std::cin >> input;
return input;


int main()
std::string input = getInput();


There are several portions of main that could become functions.



Declare Variable when needed



In the function convertToBinary the integer variables i and r are declared at the beginning of the function. They are only needed within the for loop.



 for (int i = 0; i < l; i++) 
int r = decimal % 2;
decimal /= 2;
str += std::to_string(r);



This is also true in the main function for i and other variables.



The contents of the then clause and the else could both be moved into functions.



Does the inner if statement (if (i == length - 1)) need to be within the for loop or could it be executed after the for loop is done? You might want to think about loop invariants.



Reduce Complexity When You Can



In the function bits checking from the top down might make reading easier because the top limit isn't needed



 if (d > 65535) 
l = 32;
else if (d > 255)
l = 16;
else
l = 8;






share|improve this answer











$endgroup$












    Your Answer





    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    J Pex is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215455%2fprogram-that-outputs-binary-values-of-input%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0












    $begingroup$

    The first 3 lines in main can be turned into a function:



    std::string getInput()

    std::string input;
    std::cout << "------------ Input -----------" << std::endl;
    std::cin >> input;
    return input;


    int main()
    std::string input = getInput();


    There are several portions of main that could become functions.



    Declare Variable when needed



    In the function convertToBinary the integer variables i and r are declared at the beginning of the function. They are only needed within the for loop.



     for (int i = 0; i < l; i++) 
    int r = decimal % 2;
    decimal /= 2;
    str += std::to_string(r);



    This is also true in the main function for i and other variables.



    The contents of the then clause and the else could both be moved into functions.



    Does the inner if statement (if (i == length - 1)) need to be within the for loop or could it be executed after the for loop is done? You might want to think about loop invariants.



    Reduce Complexity When You Can



    In the function bits checking from the top down might make reading easier because the top limit isn't needed



     if (d > 65535) 
    l = 32;
    else if (d > 255)
    l = 16;
    else
    l = 8;






    share|improve this answer











    $endgroup$

















      0












      $begingroup$

      The first 3 lines in main can be turned into a function:



      std::string getInput()

      std::string input;
      std::cout << "------------ Input -----------" << std::endl;
      std::cin >> input;
      return input;


      int main()
      std::string input = getInput();


      There are several portions of main that could become functions.



      Declare Variable when needed



      In the function convertToBinary the integer variables i and r are declared at the beginning of the function. They are only needed within the for loop.



       for (int i = 0; i < l; i++) 
      int r = decimal % 2;
      decimal /= 2;
      str += std::to_string(r);



      This is also true in the main function for i and other variables.



      The contents of the then clause and the else could both be moved into functions.



      Does the inner if statement (if (i == length - 1)) need to be within the for loop or could it be executed after the for loop is done? You might want to think about loop invariants.



      Reduce Complexity When You Can



      In the function bits checking from the top down might make reading easier because the top limit isn't needed



       if (d > 65535) 
      l = 32;
      else if (d > 255)
      l = 16;
      else
      l = 8;






      share|improve this answer











      $endgroup$















        0












        0








        0





        $begingroup$

        The first 3 lines in main can be turned into a function:



        std::string getInput()

        std::string input;
        std::cout << "------------ Input -----------" << std::endl;
        std::cin >> input;
        return input;


        int main()
        std::string input = getInput();


        There are several portions of main that could become functions.



        Declare Variable when needed



        In the function convertToBinary the integer variables i and r are declared at the beginning of the function. They are only needed within the for loop.



         for (int i = 0; i < l; i++) 
        int r = decimal % 2;
        decimal /= 2;
        str += std::to_string(r);



        This is also true in the main function for i and other variables.



        The contents of the then clause and the else could both be moved into functions.



        Does the inner if statement (if (i == length - 1)) need to be within the for loop or could it be executed after the for loop is done? You might want to think about loop invariants.



        Reduce Complexity When You Can



        In the function bits checking from the top down might make reading easier because the top limit isn't needed



         if (d > 65535) 
        l = 32;
        else if (d > 255)
        l = 16;
        else
        l = 8;






        share|improve this answer











        $endgroup$



        The first 3 lines in main can be turned into a function:



        std::string getInput()

        std::string input;
        std::cout << "------------ Input -----------" << std::endl;
        std::cin >> input;
        return input;


        int main()
        std::string input = getInput();


        There are several portions of main that could become functions.



        Declare Variable when needed



        In the function convertToBinary the integer variables i and r are declared at the beginning of the function. They are only needed within the for loop.



         for (int i = 0; i < l; i++) 
        int r = decimal % 2;
        decimal /= 2;
        str += std::to_string(r);



        This is also true in the main function for i and other variables.



        The contents of the then clause and the else could both be moved into functions.



        Does the inner if statement (if (i == length - 1)) need to be within the for loop or could it be executed after the for loop is done? You might want to think about loop invariants.



        Reduce Complexity When You Can



        In the function bits checking from the top down might make reading easier because the top limit isn't needed



         if (d > 65535) 
        l = 32;
        else if (d > 255)
        l = 16;
        else
        l = 8;







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 6 hours ago

























        answered 6 hours ago









        pacmaninbwpacmaninbw

        5,21821537




        5,21821537




















            J Pex is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            J Pex is a new contributor. Be nice, and check out our Code of Conduct.












            J Pex is a new contributor. Be nice, and check out our Code of Conduct.











            J Pex is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215455%2fprogram-that-outputs-binary-values-of-input%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            कुँवर स्रोत दिक्चालन सूची"कुँवर""राणा कुँवरके वंशावली"

            Why is a white electrical wire connected to 2 black wires?How to wire a light fixture with 3 white wires in box?How should I wire a ceiling fan when there's only three wires in the box?Two white, two black, two ground, and red wire in ceiling box connected to switchWhy is there a white wire connected to multiple black wires in my light box?How to wire a light with two white wires and one black wireReplace light switch connected to a power outlet with dimmer - two black wires to one black and redHow to wire a light with multiple black/white/green wires from the ceiling?Ceiling box has 2 black and white wires but fan/ light only has 1 of eachWhy neutral wire connected to load wire?Switch with 2 black, 2 white, 2 ground and 1 red wire connected to ceiling light and a receptacle?

            चैत्य भूमि चित्र दीर्घा सन्दर्भ बाहरी कडियाँ दिक्चालन सूची"Chaitya Bhoomi""Chaitya Bhoomi: Statue of Equality in India""Dadar Chaitya Bhoomi: Statue of Equality in India""Ambedkar memorial: Centre okays transfer of Indu Mill land"चैत्यभमि