我想将整数转换为二进制字符串,然后将整数字符串的每个位存储到给定大小的整数数组的元素.我确信输入整数的二进制表达式不会超过指定数组的大小.如何在c ++中执行此操作?
伪代码:
int value = ???? // assuming a 32 bit int
int i;
for (i = 0; i < 32; ++i) {
array[i] = (value >> i) & 1;
}
Run Code Online (Sandbox Code Playgroud)
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] << ' ';
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 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;
}
Run Code Online (Sandbox Code Playgroud)
这里有几点需要注意:首先,bitset 声明语句中的 32 告诉编译器你想要 32 位来表示你的数字,所以即使你的数字需要更少的位来表示,bitset 变量也会有 32 位,可能是许多前导零。其次,bitset 是一种非常灵活的二进制处理方式,您可以将字符串作为输入或数字,同样您可以将 bitset 用作数组或字符串。这是一个非常方便的库。您可以将 bitset 变量 A 打印为 as
cout<<A;
并查看它是如何工作的。