简体   繁体   中英

C++ bitwise bools

I am trying to figure out an efficient way to create a Boolean type which suits byte operations. for example:

unsigned char TRUE_BOOL = ~unsigned char(0);
unsigned char FALSE_BOOL = unsigned char(0);

Now I want to have the following expression return one of the defined BOOL's- so if for example I use the expression 5 < 10 this will return one of my bitwise BOOL's rather than the standard bools. I want this in order to be able to replace if statements with bitwise operations :

//---------------parameter definitions
unsigned char a = 10;
unsigned char b = 20;

//---------------if statement approach
if(a < b){
    unsigned char Result = 13;
}else{
    unsigned char Result = 17;
}

//---------------bitwise approach
unsigned char Result = ((a < b) & 13) | ((a >= b) & 17);

What are some of the ways this (ie returning my BOOL rather than the standard) could be implemented? I have some ideas but I wanted to know if perhaps some better approach exists.

You can create a custom boolean class that does result in ~0 or 0 when implicitly converted to an unsigned int, like so:

class BOOL {
    unsigned int value;

public:
    BOOL(bool value): value(value ? ~0 : 0) {}

    operator unsigned int() {
        return value;
    }
};

Then you could write:

unsigned char Result = (BOOL(a < b) & 13) | (BOOL(a >= b) & 17);

Which does what you want. I wouldn't recommend this however, as the compiler will already do these kinds of optimizations for you. For example, instead of using the above way of writing the expression with the & -operator, you could instead write:

unsigned char Result = ((a < b) * 13) | ((a >= b) * 17);

But as mentioned in the comments, the lack of if -statements doesn't mean this couldn't still contains conditional branches. One thing to note though is that the difference between 13 and 17 is just 4 You could thus write:

unsigned char Result = 13 + ((a >= b) << 2);

All these approaches are optimized by the compiler to generate the exact same instructions, as can be seen on godbolt.org .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM