int temp = 0x5E; // in binary 0b1011110.有没有这样一种方法来检查temp中的位3是1还是0,而不需要位移位和掩码。
我只想知道是否有一些内置的函数,或者我被迫自己写一个。
发布于 2020-09-30 18:23:55
先例答案向您展示了如何处理位校验,但更常见的情况是,它都是关于以整数编码的标志,这在任何先例案例中都没有很好的定义。
在一个典型的场景中,标志被定义为整数本身,对于它引用的特定位,位被定义为1。在下面的示例中,您可以检查整数是否有标志列表中的任何标志(多个错误标志连接在一起),或者每个标志是否都在整数中(多个成功标志连接在一起)。
下面是一个如何处理整数中的标志的示例。
这里提供了一个现场示例:https://rextester.com/XIKE82408
//g++  7.4.0
#include <iostream>
#include <stdint.h>
inline bool any_flag_present(unsigned int value, unsigned int flags) {
    return bool(value & flags);
}
inline bool all_flags_present(unsigned int value, unsigned int flags) {
    return (value & flags) == flags;
}
enum: unsigned int {
    ERROR_1 = 1U,
    ERROR_2 = 2U, // or 0b10
    ERROR_3 = 4U, // or 0b100
    SUCCESS_1 = 8U,
    SUCCESS_2 = 16U,
    OTHER_FLAG = 32U,
};
int main(void)
{
    unsigned int value = 0b101011; // ERROR_1, ERROR_2, SUCCESS_1, OTHER_FLAG
    unsigned int all_error_flags = ERROR_1 | ERROR_2 | ERROR_3;
    unsigned int all_success_flags = SUCCESS_1 | SUCCESS_2;
    
    std::cout << "Was there at least one error: " << any_flag_present(value, all_error_flags) << std::endl;
    std::cout << "Are all success flags enabled: " << all_flags_present(value, all_success_flags) << std::endl;
    std::cout << "Is the other flag enabled with eror 1: " << all_flags_present(value, ERROR_1 | OTHER_FLAG) << std::endl;
    return 0;
}https://stackoverflow.com/questions/523724
复制相似问题