将整数转换为二进制并将其存储在指定大小的整数数组中:c++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14104208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:58:21  来源:igfitidea点击:

Convert integer to binary and store it in an integer array of specified size:c++

c++binary

提问by lovespeed

I want to convert an integer to binary string and then store each bit of the integer string to an element of a integer array of a given size. I am sure that the input integer's binary expression won't exceed the size of the array specified. How to do this in c++?

我想将整数转换为二进制字符串,然后将整数字符串的每一位存储到给定大小的整数数组的元素中。我确信输入整数的二进制表达式不会超过指定数组的大小。如何在 C++ 中做到这一点?

回答by mah

Pseudo code:

伪代码:

int value = ????  // assuming a 32 bit int
int i;

for (i = 0; i < 32; ++i) {
    array[i] = (value >> i) & 1;
}

回答by Mooing Duck

template<class output_iterator>
void convert_number_to_array_of_digits(const unsigned number, 
         output_iterator first, output_iterator last) 
{
    const unsigned number_bits = CHAR_BIT*sizeof(int);
    //extract bits one at a time
    for(unsigned i=0; i<number_bits && first!=last; ++i) {
        const unsigned shift_amount = number_bits-i-1;
        const unsigned this_bit = (number>>shift_amount)&1;
        *first = this_bit;
        ++first;
    }
    //pad the rest with zeros
    while(first != last) {
        *first = 0;
        ++first;
    }
}

int main() {
    int number = 413523152;
    int array[32];
    convert_number_to_array_of_digits(number, std::begin(array), std::end(array));
    for(int i=0; i<32; ++i)
        std::cout << array[i] << ' ';
}

Proof of compilation here

编译证明在这里

回答by Aravind

You could use C++'s bitset library, as follows.

您可以使用 C++ 的bitset 库,如下所示。

#include<iostream>
#include<bitset>

int main()
{
  int N;//input number in base 10
  cin>>N;
  int O[32];//The output array
  bitset<32> A=N;//A will hold the binary representation of N 
  for(int i=0,j=31;i<32;i++,j--)
  {
     //Assigning the bits one by one.
     O[i]=A[j];
  }
  return 0;
}

A couple of points to note here: First, 32 in the bitset declaration statement tells the compiler that you want 32 bits to represent your number, so even if your number takes fewer bits to represent, the bitset variable will have 32 bits, possibly with many leading zeroes. Second, bitset is a really flexible way of handling binary, you can give a string as its input or a number, and again you can use the bitset as an array or as a string.It's a really handy library. You can print out the bitset variable A as cout<<A;and see how it works.

这里有几点需要注意:首先,bitset 声明语句中的 32 告诉编译器你想要 32 位来表示你的数字,所以即使你的数字需要更少的位来表示,bitset 变量也会有 32 位,可能是许多前导零。其次,bitset 是一种非常灵活的二进制处理方式,您可以将字符串作为其输入或数字,同样您可以将 bitset 用作数组或字符串。这是一个非常方便的库。您可以将 bitset 变量 A 打印为 as cout<<A;并查看它是如何工作的。

回答by Alfred

You can do like this:

你可以这样做:

while (input != 0) {

        if (input & 1)
            result[index] = 1; 
        else
            result[index] =0;
   input >>= 1;// dividing by two
   index++;
}

回答by RageD

As Mat mentioned above, an intis already a bit-vector (using bitwise operations, you can check each bit). So, you can simply try something like this:

正如 Mat 上面提到的, anint已经是一个位向量(使用按位运算,您可以检查每一位)。所以,你可以简单地尝试这样的事情:

// Note: This depends on the endianess of your machine
int x = 0xdeadbeef; // Your integer?
int arr[sizeof(int)*CHAR_BIT];
for(int i = 0 ; i < sizeof(int)*CHAR_BIT ; ++i) {
  arr[i] = (x & (0x01 << i)) ? 1 : 0; // Take the i-th bit
}

回答by Grijesh Chauhan

Decimal to Binary: Size independent

十进制到二进制:大小无关

Two ways: both stores binary represent into a dynamic allocated array bits(in msh to lsh).

两种方式:两者都将二进制表示存储到动态分配的数组中bits(在 msh 到 lsh 中)。

First Method:

第一种方法:

#include<limits.h> // include for CHAR_BIT
int* binary(int dec){
  int* bits = calloc(sizeof(int) * CHAR_BIT, sizeof(int));
  if(bits == NULL) return NULL;
  int i = 0;

  // conversion
  int left = sizeof(int) * CHAR_BIT - 1; 
  for(i = 0; left >= 0; left--, i++){
    bits[i] = !!(dec & ( 1u << left ));      
  }

  return bits;
}

Second Method:

第二种方法:

#include<limits.h> // include for CHAR_BIT
int* binary(unsigned int num)
{
   unsigned int mask = 1u << ((sizeof(int) * CHAR_BIT) - 1);   
                      //mask = 1000 0000 0000 0000
   int* bits = calloc(sizeof(int) * CHAR_BIT, sizeof(int));
   if(bits == NULL) return NULL;
   int i = 0;

   //conversion 
   while(mask > 0){
     if((num & mask) == 0 )
         bits[i] = 0;
     else
         bits[i] = 1;
     mask = mask >> 1 ;  // Right Shift 
     i++;
   }

   return bits;
}

回答by perry_the_python

This is what I use, it also lets you give the number of bits that will be in the final vector, fills any unused bits with leading 0s.

这就是我使用的,它还允许您给出最终向量中的位数,用前导 0 填充任何未使用的位。

std::vector<int> to_binary(int num_to_convert_to_binary, int num_bits_in_out_vec)
{
    std::vector<int> r;

    // make binary vec of minimum size backwards (LSB at .end() and MSB at .begin())
    while (num_to_convert_to_binary > 0)
    {
        //cout << " top of loop" << endl;
        if (num_to_convert_to_binary % 2 == 0)
            r.push_back(0);
        else
            r.push_back(1);
        num_to_convert_to_binary = num_to_convert_to_binary / 2;
    }

    while(r.size() < num_bits_in_out_vec)
        r.push_back(0);

    return r;
}

回答by Brandon

I know it doesn't add as many Zero's as you wish for positive numbers. But for negative binary numbers, it works pretty well.. I just wanted to post a solution for once :)

我知道它不会像您希望的正数那样添加尽可能多的零。但是对于负二进制数,它工作得很好..我只想发布一次解决方案:)

int BinToDec(int Value, int Padding = 8)
{
    int Bin = 0;

    for (int I = 1, Pos = 1; I < (Padding + 1); ++I, Pos *= 10)
    {
        Bin += ((Value >> I - 1) & 1) * Pos;
    }
    return Bin;
}