0
Help turning integers into binary in c++, my binary numbers come out backwards.
#include <iostream> using namespace std; void binary_counter(int input) { unsigned short int output = 0; // unsigned: can only hold positive values cout << "The binary equivalent of " << input << " is "; while (input > 0) { output = input % 2; cout << output; input /= 2; //same as input = input / 2; } cout << endl; } int main() { int num; cout << "Enter the number : "; cin >> num; binary_counter(num); return 0; }
5 Réponses
+ 4
Your output has either 0 or 1 in it. Add '0' to it yields '0' or '1' as an integer (48 or 49). (char)(48) forces the integer to a character '0' (49 becoming '1'.) That character is added in front of the existing string, since we started with the least significant digit.
5 would assign output to 1, 0, and finally 1. Result starts as "", "1", "01", and finally "101".
+ 6
Updated lines commented with ALL uppercase.
https://code.sololearn.com/crgJw2EstKSh
+ 1
I understand why you added most things, but I'm having difficulty understanding this line... result = (char)(output + '0') + result;
Thank you so much for the help!
0
Save the binary digits in a string or vector and reverse it after the while loop has finished.
0
I been trying to turn it into a string but its just not coming right...