0

我想将十进制值转换为 16 位二进制值。我在另一个中使用了这个代码。

      #include <iostream>
      #include <bitset>

      int main() { 
      int x = 5;

      std::bitset<8> bin_x(x);
      std::cout << bin_x;

      return 0;
      }

这是会员发布的代码。我想在循环中使用它并将 bin_x 的值存储在 16 个二维字符数组中。怎么做到呢?这就是我在做什么

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

     int main(){

int DecimalArray[] = {1,2,3,4,5,22,555,85,18,741}; //Create an array of decimal   numbers.

const int ArrayLen = sizeof(DecimalArray)/sizeof(int); //Store the size of the Decimal Array in a constant
 //strcpy(BinaryArray[i], "0000000000000000");
char BinaryArray[ArrayLen][16]; //Create an array of the same length for binary nos.


for(int i = 0; i<ArrayLen; i++)
{

    int CurrentDec = DecimalArray[i]; //Store current Decimal number in  CurrentDec variable

    strcpy(BinaryArray[i], "0000000000000000");

std::bitset<16> bin_x(CurrentDec);
cout<< "bin"<<bin_x<< endl;
for (int j = 0; j<15; j++)
         {
 bin_x=BinaryArray[i][j];


    cout<< "b1"<< BinaryArray[i] << endl;
     }


cout<<"The Decimal numbers and their Binary Equivalents are:\n\n";
cout<<"Decimal  Binary \n\n";
}

//Output both arrays
for( i = 0; i<ArrayLen; i++){
    cout<<DecimalArray[i]<<"\t "<<BinaryArray[i]<<endl;
}

cin.get();
return 0;

      }
       but i do not get the value in BinaryArray. kindly help me with it, its very urgent. Thanks!
4

1 回答 1

1
           #include<iostream>

           using namespace std;

           #include <bitset>

           int main(){

           int DecimalArray[] = {1,2,3,4,5,22,555,85,18,741}; //Create an array of decimal numbers.

            const int ArrayLen = sizeof(DecimalArray)/sizeof(int); //Store the size of the Decimal Array in a constant
           //strcpy(BinaryArray[i], "0000000000000000");
           char BinaryArray[ArrayLen][17]; //Create an array of the same length for binary nos.

           int i;

           for(i = 0; i<ArrayLen; i++)
            {

           int CurrentDec = DecimalArray[i]; //Store current Decimal number in       CurrentDec variable
           int index = 1, CurrentBin = 0;
           strcpy(BinaryArray[i], "0000000000000000");

           std::bitset<16> bin_x(CurrentDec);
           cout<< "bin"<<bin_x<< endl;
           for (int j = 0; j<16; j++)
           {
            if (bin_x[15-j])
               {

                 BinaryArray[i][j] = '1';
                  }



                  cout<< "b1"<< BinaryArray[i][j]<<endl ;

                    }

                     }


               cout<<"The Decimal numbers and their Binary Equivalents are:\n\n";
               cout<<"Decimal Binary \n\n";


               //Output both arrays
               for( i = 0; i<ArrayLen; i++){
               cout<<DecimalArray[i]<<"\t "<<BinaryArray[i]<<endl;
                }



               cin.get();
               return 0;

                }
于 2012-08-05T20:15:10.640 回答