如何从C中的整数值得到逐位数据? [英] How do I get bit-by-bit data from an integer value in C?

查看:74
本文介绍了如何从C中的整数值得到逐位数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要解开一个十进制数位。

I want to extract bits of a decimal number.

例如,7是二进制的0111,我想获得0 1 1 1储存在布尔所有位。我该怎么办呢?

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,一个循环是不是一个好的选择,我可以做这个东西?

OK, a loop is not a good option, can I do something else for this?

推荐答案

如果你想n的k位,然后执行

If you want the k-th bit of n, then do

(n & ( 1 << k )) >> k

下面我们创建一个面膜,敷面膜N,然后右移蒙面价值得到公正,我们希望该位。我们可以更充分地写出来的:

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.

下面是一个程序:

#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");
}

这篇关于如何从C中的整数值得到逐位数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆