How do I get bit-by-bit data from an integer value in C?

后端 未结 8 1102
时光说笑
时光说笑 2020-11-30 17:36

I want to extract bits of a decimal number.

For example, 7 is binary 0111, and I want to get 0 1 1 1 all bits stored in bool. How can I do so?

OK, a loop is

相关标签:
8条回答
  • 2020-11-30 18:01

    Using std::bitset

    int value = 123;
    std::bitset<sizeof(int)> bits(value);
    std::cout <<bits.to_string();
    
    0 讨论(0)
  • 2020-11-30 18:02

    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.

    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");
    }
    
    0 讨论(0)
提交回复
热议问题