PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 13, 2022

[FIXED] Why won't my decimal to binary output reverse?

 August 13, 2022     binary, c++, decimal     No comments   

Issue

I am doing some simple decimal to binary conversion using a while loop, and I realized that my output from the loop needs to be reversed, which i did so by creating a stringstream and then moving my generated int into a stringstream which then converts it to a string and then reverses the order for the string to get the correct binary value... but when I actually run the code, there's like a random 1 or 0 out in front of everything...

#include <iostream>
#include <sstream>
#include <algorithm>

int main() {
    std::stringstream ss;
    int decimal;
    int binary;
    std::cout<< "\n Please enter decimal value: ";
    std::cin >> decimal;
    std::cout << "\n The binary equivalent of " << decimal << " is ";
    while(decimal > 0 ) {
        binary = decimal % 2;

        decimal/= 2;

        std::cout << binary;

    }
    ss << binary;
    std::string binary_string = ss.str();
    std::reverse(binary_string.begin(), binary_string.end());
    std::cout << binary_string;
}

For example, if I input an 11 I get this:

Please enter decimal value: 11

The binary equivalent of 11 is 11011

For 12:

Please enter decimal value: 12

The binary equivalent of 12 is 00111

Solution

The extra bit is coming from

ss << binary;
string binary_string = ss.str();
reverse(binary_string.begin(), binary_string.end());
cout << binary_string;

after the loop. binary is either going to contain a 1 or a 0 and converting that to string and reversing it is going to give you the same thing. You need to move ss << binary; into the loop so it contains all the binary digits you generate.



Answered By - NathanOliver
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing