1

my task is to convert decimal numbers to binary, but as we are beginners in programming I'm not allowed to use arrays, functions, etc. Just for and if and basic operations.

My code is:

#include <iostream>
int main()
{
   int n;
   int b;
   
   std::cin >> n;
   
   for (int i=n; n>0; --i) {
       
     b = n%2;
     std::cout << b;
     n = n/2;
   
   }

   return 0;
}

It works, but it gives me the binary number in the wrong order, e.g. it's 0001 representing 4 instead of 1000. Could anyone help me please?

JaMiT
  • 14,422
  • 4
  • 15
  • 31
kp00
  • 11
  • 1
  • 4
  • 1
    Understand what your loop does. Consider learning how to use a debugger to explore why something deviated from what you expected. It's a really handy tool! Your loop basically prints out the correct binary representation but in the reverse order. How can you fix that without an array (that you can print in reverse)? I'll let you think about that for some time... – Arrow Oct 01 '20 at 19:49
  • Assuming that `int` is 32 bits (still a reasonable assumption) start to print bit bit 32 of the number. Then bit 31. And so on, down to bit 1. Use shifts and maskin to get the bits. – Some programmer dude Oct 01 '20 at 19:49
  • I don't know what you're trying to say. Maybe I could change my loop to i=1; i<=n; ++i but that makes it even worse.... – kp00 Oct 01 '20 at 19:55
  • My problem is that my output should not output the leading zeros... – kp00 Oct 01 '20 at 19:58
  • 2
    I've reverted your question to the question that others had answered. It is rude to invalidate existing answers by changing the question. If you have a follow-up question, please start a *new* question for it (but perhaps give that debugger suggestion a try first). – JaMiT Oct 01 '20 at 23:34
  • See https://stackoverflow.com/a/64195472/2785528 for my recursive solution – 2785528 Oct 04 '20 at 14:00

3 Answers3

2

The reason why your loop doesn't print what you expect is because it's essentially working in reverse i.e. printing from LSB (least significant bit) to MSB (most significant bit). Have a good look and explore it yourself.

So, what's the solution to printing the binary of number in reverse without the help arrays, etc?

int main () {
    int n;
    std::cin >> n;

    // assuming integers are 32-bit
    // works for both positive and negative numbers
    for (int i = 31; i >= 0; --i) {
        if (n & (1 << i))
            std::cout << 1;
        else
            std::cout << 0;
    }

    return 0;
}

Like @Some programmer dude, use bit shifts and other bit arithmetic operators. Learn more about them here and here.

Arrow
  • 389
  • 2
  • 12
  • What is the part ? 1 : 0 What does that mean? I cant use it because we haven't had that yet... – kp00 Oct 01 '20 at 20:01
  • @kp00 My bad! I forgot the fact that you might not have learnt about the [ternary operator](https://www.geeksforgeeks.org/conditional-or-ternary-operator-in-c-c/). I'll edit my post to make it use an if-else statement. – Arrow Oct 01 '20 at 20:04
  • What does the & mean? – kp00 Oct 01 '20 at 20:08
  • @kp00: `&` is the binary AND operator; `&&` is the logical AND operator. – Andreas Wenzel Oct 01 '20 at 20:18
  • @kp00 `&` is the symbol for binary `AND`. `<<` is the left bitshift operator. `1 << i` is the equivalent of multiplying 1 with 2 to the i'th power. Please google the things you don't understand. You will most likely find what you need as a beginner if you search up things on your own, and it's a great habit to have as a programmer. Also, please do go through the links I've attached previously. – Arrow Oct 01 '20 at 20:21
  • Thank you. Now I've just got one problem: It should not output leading zeros. I have really no clue, if i delete the else statement then it's completely wrong. – kp00 Oct 01 '20 at 20:27
  • @kp00 I believe the instructor/teacher who asked you to solve this question expected you to solve it. If I (or anyone else) is going to be doing the solving, it fails the purpose of you trying to understand programming. Think about what the code is doing and try a lot more things the removing an else statement from here and there. (Hint: Until the first time a 1 is printed, don't print any zeroes. How do you do that? Use a boolean variable initially set to false that gets set to true after you print the first 1. if-else statements will be your friend) – Arrow Oct 01 '20 at 20:41
  • I'm giving up now, I've started programming a week ago and for me that's all cryptography. I don't even understand the code I wrote myself. But thank you anyway. – kp00 Oct 01 '20 at 20:47
  • Guys, I'm trying. What means the & -operator? I found in the web that it is a binary AND, as you explained, but the values in my code are no binaries, so what does it check then? Does it check if it's the same value? Or does it check if n and 2^i have the same bit value there? – kp00 Oct 01 '20 at 21:01
0
    int x;
    while(std::cin >> x) {
        auto b = std::bitset<sizeof(x) * 8>{static_cast<unsigned>(x)};
        std::cout << x << ' ' << b << '\n';
    }

https://godbolt.org/z/njzTPo

Marek R
  • 32,568
  • 6
  • 55
  • 140
  • If the poster hasn't learned about arrays, it's highly unlikely they've learned about `std::bitset`, especially if they specifically mentioned they can't use functions and needed to do it with `for` and `if` and basic operations. – Ken White Oct 02 '20 at 01:28
0

This is my solution, only using while loops (which I'm hoping is what you mean by basic) :

#include<iostream>
#include<cmath>
using namespace std;

int main() {
int dec, bin = 0, r = 1, p = 0;
cin >> dec;

while(dec > 0){
    while ((r * 2) <= dec) {
        r *= 2;
        p += 1;
    }
    dec -= r;
    bin = bin + (pow(10, p));

    r = 1;
    p = 0;
}
cout << bin;
return 0;
}

It works by finding the largest multiple of 2 smaller than the decimal number we have, and then subtracting it from the decimal. Then it adds the corresponding multiple of 10 to the binary number.

Eg. If dec = 45, first r = 32, which means 10 ^ 6 = 100000 (binary representation of 32) is added to the bin (initialized to 0). This goes on until dec = 0.

Note : If you are not allowed to use a library function to calculate multiples of 10, you can easily do so running another loop, which you might know.