Help turning integers into binary in c++, my binary numbers come out backwards. | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
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; }

22nd Mar 2018, 4:36 PM
Alejandro Martinez
Alejandro Martinez - avatar
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".
23rd Mar 2018, 3:00 AM
John Wells
John Wells - avatar
+ 6
Updated lines commented with ALL uppercase. https://code.sololearn.com/crgJw2EstKSh
22nd Mar 2018, 6:29 PM
John Wells
John Wells - avatar
+ 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!
23rd Mar 2018, 1:55 AM
Alejandro Martinez
Alejandro Martinez - avatar
0
Save the binary digits in a string or vector and reverse it after the while loop has finished.
22nd Mar 2018, 5:13 PM
Alex
Alex - avatar
0
I been trying to turn it into a string but its just not coming right...
22nd Mar 2018, 5:20 PM
Alejandro Martinez
Alejandro Martinez - avatar