c - 枚举类型的位运算

标签 c bit-manipulation enumerated-types

我在开始使用我的实验室时遇到了一些问题。实验室有以下说明:

Given a value int input = 0b10010110 determine what sports an individual likes. Assume there will be no errors in this input. From left to right, each position represents the following: Football, Baseball, Volleyball, Swimming, Softball, Soccer, Hockey, Lacrosse.

If there is a 1 is in that position, then the person likes that sport. Based on the “binary” input given, output to the screen all of the sports that the user enjoys. For the given binary number, the user likes, football, swimming, soccer and hockey.

  • Do not make an array of characters.

  • Be sure to use an enumerated data type.

我不确定如何比较字符串的每个位置来判断它是 1 还是 0。我的一个想法是使用枚举类型,将每个运动设置为十位数字,其中只有其合适的位置是1

enum sport{
    Football = 0010000000,
    Baseball = 0001000000,
    Volleyball = 0000100000, 
    ... , 
    Lacrosse = 0000000001
};

然后,我将在给定值“输入”上向左/向右移动适当的次数,仅将指定位置保留为其原始值,并将所有其他值设置为 0。对于足球:

input << 2; input >> 9; input << 7;

因此新的设置值为0010000000。然后我就可以比较整个数字。对于每种情况我都必须这样做,但我想不出不同的方法来做到这一点。

我已经彻底放弃了吗?是否有更实用的方法来使用位运算检查每个位置的值?感谢您提前提供的任何帮助。

最佳答案

使用按位与运算符&:

if (input & Football) {
    // Football bit is set
} else {
    // Football bit is not set
}

另请注意,0b 前缀是编译器扩展,但不是标准 C。在 enum 值中,是以 0 开头的数字code> 前缀是八进制格式(你必须解决这个问题)。我建议您使用十六进制格式进行位操作。

关于c - 枚举类型的位运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12773225/

相关文章:

c - 在 Linux 终端中打开用户指定的文件名

c - : (*) as part as type in C 是什么意思

c++ - 子集相关的位操作

c++ - 枚举数据和 vector 错误 : expression must be a modifiable lvalue

c - 如何将字符串从 C 传递给 swift?

c - 如何在使用 fgets() 读取一行后返回到上一行的开头?

c++ - 以通用方式覆盖整数中的一系列位

mysql - 在 MySQL 中对大位字符串执行按位运算?

python - 理解Python中的枚举