i want to extract bits of a decimal no.
for example 7 has a binary 0111 and i want to get 0 1 1 1 all bits stored in bool how can i do so?
OK loop is not a good option can do some this else to this?
i want to extract bits of a decimal no.
for example 7 has a binary 0111 and i want to get 0 1 1 1 all bits stored in bool how can i do so?
OK loop is not a good option can do some this else to this?
If you want the k-th bit of n, then do
(n & ( 1 << k )) >> k
Here we create a mask, apply the mask to n, and then right shift the masked value to get just the bit we want. We could write it out more fully as:
int mask = 1 << k;
int masked_n = n & mask;
int thebit = masked_n >> k;
You can read more about bit-masking here: http://en.wikipedia.org/wiki/Mask_(computing)
Here is a program:
#include <stdio.h>
#include <stdlib.h>
int *get_bits(int n, int bitswanted){
int *bits = malloc(sizeof(int) * bitswanted);
int k;
for(k=0; k<bitswanted; k++){
int mask = 1 << k;
int masked_n = n & mask;
int thebit = masked_n >> k;
bits[k] = thebit;
}
return bits;
}
int main(){
int n=7;
int bitswanted = 5;
int *bits = get_bits(n, bitswanted);
printf("%d = ", n);
int i;
for(i=bitswanted-1; i>=0;i--){
printf("%d ", bits[i]);
}
printf("\n");
}
Here's one way to do it—there are many others:
bool b[4];
int v = 7; // number to dissect
for (int j = 0; j < 4; ++j)
b [j] = 0 != (v & (1 << j));
here's a very simple way to do it;
int main() {
int s=7,l=1;
vector <bool> v;
v.clear();
while(l<=4)
{
v.push_back(s%2);
s/=2;
l++;
}
for(l=(v.size()-1);l>=0;l--)
{
cout<<v[l]<<" ";
}
return 0; }