查找位位置在32位无符号整数 [英] Finding Bit Positions in an unsigned 32-bit integer

查看:166
本文介绍了查找位位置在32位无符号整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我可能已经睡在我的CS类时,他们谈到位的位置,所以我希望有人能伸出援助之手。

I think I might have been asleep in my CS class when they talked about Bit Positions, so I am hoping someone can lend a hand.

我有一个无符号的32位整数(允许使用的值:28)

I have a unsigned 32-bit integer (Lets use the value: 28)

据一些资料我要去了,整的值包含标志指定各种事情。

According to some documentation I am going over, the value of the integer contains flags specifying various things.

位位置从1(低位)编号为32(高位)。
所有未定义的标志位被保留,必须设置为0。

Bit positions within the flag are numbered from 1 (low-order) to 32 (high-order). All undefined flag bits are reserved and must be set to 0.

我有一个表,显示标志的含义,与意为数字1-10。

I have a Table that shows the meanings of the flags, with meaning for the numbers 1-10.

我希望有人可以尝试向我解释这一切意味着,以及如何从众多类似,28找到标志值(S),根据折位的位置。

I am hoping that someone can try and explain to me what this all means and how to find the "flag" value(s) from a number like, 28, based off of bit position.

感谢

推荐答案

28皈依11100二进制。这意味着,位1和2没有设置与第3位,第4和5被设置

28 converts to 11100 in binary. That means bits 1 and 2 are not set and bits 3, 4 and 5 are set.

的几点:第一,任何人谁是真正习惯于到C通常会从0开始编号,而不是1其次,你可以测试使用按位与运算符(&放个人标志的; ),如:

A few points: first, anybody who's really accustomed to C will usually start the numbering at 0, not 1. Second, you can test of individual flags with the bitwise and operator (&), as in:

#define flag1 1    //  1 = 00 0001
#define flag2 2    //  2 = 00 0010
#define flag3 4    //  4 = 00 0100
#define flag4 8    //  8 = 00 1000
#define flag5 16   // 16 = 01 0000
#define flag6 32   // 32 = 10 0000

if (myvalue & flag1)
    // flag1 was set

if (myvalue & flag4)
    // flag4 was set

和等。你也可以检查哪些位在一个循环设置:

and so on. You can also check which bits are set in a loop:

#include <stdio.h>

int main() { 
    int myvalue = 28;
    int i, iter;

    for (i=1, iter=1; i<256; i<<=1, iter++)
        if (myvalue & i)
            printf("Flag: %d set\n", iter);
    return 0;
}

应打印:

Flag: 3 set
Flag: 4 set
Flag: 5 set

这篇关于查找位位置在32位无符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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