0

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
  • 12,175
  • 4
  • 14
  • 27
kp00
  • 1
  • 1
  • 3
  • 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... – Lost 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
  • 1
    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

1

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.

Lost Arrow
  • 339
  • 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. – Lost 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`. `< – Lost 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) – Lost 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
  • 27,988
  • 5
  • 42
  • 123
  • 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
-1

Here is code:

    #include <iostream>
    int main() {
        unsigned long long number;
        std::cin >> number;
        int i = 63;
        /*run until you find the first turn bit*/
        while ((number >> i & 1) == 0 && i >= 0) {
            i--;
        }

        if (i == 0) { // if the i == 0 means the number is 0
            std::cout << 0;
        }
        else {
            for (i; i >= 0; i--) { /* this scope for convert decimal to binary*/
                std::cout << ((number >> i & 1) != 0);
            }
        }
        return 0;
    }

The output: 4 = 0000000100 , 4000000000 = 11101110011010110010100000000000

Notice - it is for positive numbers.

About the binary AND operator - &, here is an example:

    x = 60; /* 60 = 0011 1100 */  
    y = 13; /* 13 = 0000 1101 */
    z = 0;           

    c = a & b;       /* 12 = 0000 1100 */ 

Why is the result:

    0 & 0 -> 0
    0 & 1 -> 0
    1 & 0 -> 0        
    1 & 1 -> 1        

So we will get:

    0011 1100
    0000 1101
    =========
    0000 1100
    
gera verbun
  • 124
  • 1
  • 4