0

backstory (if interested):

Recently, I have learned to write numbers in binary. So, I wanted to see if I could write every single possibility for 32-bits. So, I started, and after having successfully finished a mere 10-bits, I looked up the total amount of solutions for 32-bits. Turns out it is way way way more than I thought (well over 4 billion). So I thought a fun challenge would be to write a custom program (in C) that would calculate every single possible answer for 32-bits.

For this, I used an array with 32 items in it. Then, I check if the 32nd value is equal to 0. If it is, then I simply change it to be 1. If it is 1, I change it to be 0, and then change every item after that (equal to 1) back to zero, until I hit a 0. Here is my code :

#include <stdlib.h>

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int bits[32] = {1, 0};
    
    for (int i=0;i<3000;i++)
    {

        for (int j=0;i<32;i++)
        {
            if (bits[32] == 0)
            {
                bits[32] = 1;
            }
            else if (bits[32] == 1)
            {   
                int k = 0;
                
                for (k = 0;k<32;k++)
                {
                    int position = 32-k;
                    while(bits[position] != 0)
                    {
                        bits[position] = 0;
                    }
                    bits[position+1] = 1;
                }
            }
        }
        for (int i=0;i<32;i++)
        {
            printf("%d", bits[i]);
        }
        printf("\n");
    }
    getchar();
    return 0;
}

And then I hit a major roadblock. It didn't work at all (just plug into any IDE, run it and you will see it for yourself). It seemed perfectly logical in my head, but apparently it doesn't work like that, and I will admit I am completely lost. Does anyone know (without feeding me the whole code, I still want to do it myself) why this doesn't work, and how to fix it ? Thank you very much.

5
  • 2
    bits[32] is out of range. You can index bits[0] thru bits[31]. Similarly int position = 32-k; will be off-by-one in bits[position]. Commented Nov 18, 2021 at 19:11
  • C and C++ are two very different languages, please don't tag both. Only tag the language you're actually writing your program in. Commented Nov 18, 2021 at 19:11
  • 1
    You should explain what is wrong, rather than ask Stack Overflow readers to compile and run your code and then try to work out what's wrong. Commented Nov 18, 2021 at 19:17
  • 2
    A very overcomplicated way of doing this :). Still, (int j=0;i<32;i++) isn't this supposed to be j?. A good idea is to have different name for for indicies. The second nested for also uses i and i do not think it is intended. Commented Nov 18, 2021 at 19:18
  • Also, check the loop that sets j=0. The end condition is based in "i", which is the outer loop variable. Commented Nov 18, 2021 at 19:21

2 Answers 2

1

Well, what you asked for is already in the comments but sill if you want to check wether what you coded yelds the correct result, here is a way simpler solution.

Keep in mind that a long is also a 32 bit variable. All you have to do is to print each bit in the variable. Try this:

#include <stdio.h>
void PrintBin(unsigned long uNumber)
{
    for(unsigned long i = 0; i < 32; i++)
        printf("%lu", (uNumber & (0x80000000 >> i)) >> (31-i));
    printf("\n");
}

int main()
{
    unsigned long i = 0;
    do
    {
        printf("%lu --- ", i);
        PrintBin(i);
        i++;
    }while(i != 0);

    return 0;
}

All numbers are already in binary, you just have to print them. Well ofc if we are not talking about reading the number as a string and then convert it. Thats another story.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much !! It works basically exactly how I had envisionned my own program working. I have to admit, I don't really understand how it works, so I will research that for further uses in the future.
@Lalaryk read geeksforgeeks.org/bitwise-operators-in-c-cpp about how to do bit operations. If you understand bitwise operations, you will also understand (uNumber & (0x80000000 >> i)) >> (31-i)
@Lalaryk meh forget that link i think wikipedia is better for starting this out en.wikipedia.org/wiki/Bitwise_operations_in_C.
that is very helpful thanks a lot :)
0

Binary math is just like decimal math. To increment a number is the same as adding 1. As you probably learned in school, you just add to the first digit, and if it's greater than 9 you carry the 1 to the next digit and add to it the same way. Keep going until you have no more to carry over.

The difference for binary is that you only have 0 and 1, so adding 1 + 1 gives you 0 with a 1 to carry over.

To see how a loop would do this, you would normally add 00...001 to your bits, and have a loop to keep track of the carry (initially 0) and add it to the next bit, but you can simplify things by starting with a carry of 1 (it replaces your initial 00...001 that you're adding). It would look like this:

    uint8_t carry = 1;
    for (int bit_idx = 0; bit_idx < 32; bit_idx++) {
        const uint8_t bit = bits[bit_idx];
        /*
            carry  bit    carry bit
              1  +  1   =   1    0
              1  +  0   =   0    1
              0  +  1   =   0    1
              0  +  0   =   0    0
         */
        if ((1 == bit && 1 == carry) || (0 == bit && 0 == carry)) {
            bits[bit_idx] = 0;
            // keep carry to the next digit.
        } else {
            bits[bit_idx] = 1;
            // If you wanted, you could 'break' here instead.
            carry = 0;
        }
    }
    // Print most significant first to look normal.
    for (int bit_idx = 31; bit_idx >= 0; bit_idx--) {
        printf("[%d]", bits[bit_idx]);
    }
    printf("\n");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.