简体   繁体   中英

Store 3 bit binary numbers in C++ array

I have a program that takes 2 inputs, N and myarray[ ].

    cin >> N; 
    cin >> myarray[];

In this example say, N=3 which means an integer array of size 3 has to be allocated and suppose that the entries of myarray[ ] are {1,2,3}.

Now I have a function createsubset() that creates all the possible subsets of the entries {1,2,3}. The logic that I am following is:

Total number of subsets of a set containing n elements is m=2^n, because an element can be either present or absent in a subset.

So, when m=7 and corresponding binary notation is 111. Now iterate from m=0 to m=7 to generate all the subsets(except for the set itself which is outcome of m=8): Example:

     m=0, binary=000, subset={ }
     m=1, binary=001, subset={c}
     m=2, binary=010, subset={b}
     m=3, binary=011, subset={b,c}

and so on.

This is done by a function generate() that iterates from m=0 to m=8.

      void generate()
      {
        for(m=0; m<8; m++)
        {
           decimaltobinary(m);

        }
      }

Now, I have to store the output of decimaltobinary() function (which is a 3-bit binary number) in an array which I will use later to create subsets. This is the part where I am stuck right now. Can we store a multibit binary number in an array and use it directly? Please help me regarding this. Any suggestion regarding the createsubset() fuction is also welcomed.

Numbers in C/C++ are stored in binary so there is no need to "convert" them. You can use any C/C++ unsigned integral type you want to to store a 3 bit number so, for example, storing them in std::vector<unsigned char> would work fine.

Along this line, rather than storing the numbers you read into an array [fixed size container] consider storing them in a vector [variable size container] because you don't know the size "up front"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM