Reputation: 11
I need to put 32 bits of integers into a list. Problem is, I can't seem to fill that list up properly.
Ex. I need to get from this: 01000100011100111111000000000000
to this: list[0]=0
, list[1]=1
, list[2]=0
, list[3]=0
, and so on.
The number is being given to me as an integer through standard output.
Here is my go at it:
int binary;
cin << binary;
int *list = new int [32];
for (int i = 31; i >= 0; i--) {
list[i] = binary % 10;
binary /= 10;
}
for (int i = 0; i < 32; i++) {
cout << list[i];
cout << endl;
}
Let me know what I'm doing wrong.
Upvotes: 1
Views: 10162
Reputation: 24133
Use std::bitset
.
#include <bitset>
int main() {
std::bitset<32> bits("01000100011100111111000000000000");
}
Upvotes: 1
Reputation: 13773
This part:
int *list = new int [4];
creates an array that is indexed from 0 to 3 and You're trying to access list[4] later.
Upvotes: 2
Reputation: 11070
you should divide by 2 and start with index as 3
for(i=3;i>=0;i--)
{
list[i]=binary%2;
binary/=2;
}
This will be correct
Upvotes: 1
Reputation: 500197
The following loop results in out-of-bounds array access:
for (int i = 4; i >= 0; i--) {
list[i] = ...
list
's elements are numbered from zero to three.
Also, the following looks iffy:
list[i] = binary % 2;
binary /= 10;
The two numbers should either both be 2
or both be 10
.
Upvotes: 4