Question

I'm only a novice when it comes to bitwise math - if that's even the correct term - and was looking for a better way to do logic on an int-summed return code (as is standard for various Unix programs). I.e. the return code could be any combination of 1,2,4,8,etc

Here is my code (snippet) so far:

[...]
if (result == 0)
    //no problem
else {
    if ((result > 127) && (result % 128 == 0)) {
        // exit code contained 128
        result = result - 128;
    }
    if ((result > 63) && (result % 64 == 0)) {
        // exit code contained 64
        result = result - 64;
    }
    [...]
    if (result > 0) {
        // exit code contained 1
    }
}

I know that I should be able to do this with a bitwise operator such as AND (&) but am not sure how to go about it. I don't really understand much about bitwise operations though, i.e. if I do if (result & 64) could that also not be true if return code was 128?

Obviously my understanding of binary math is shocking, I've never really done code in this area. Just looking for some clarification of the correct bitwise method.

Was it helpful?

Solution

As pointed out in the comments by Wumpus Q Wumbley, for "standard" utilities/exit codes, there are a set of macros in <sys/wait.h> that are useful and recommended for extracting information from the exit codes. However, if the exit codes you're trying to process don't follow those usual conventions, you can extract individual bits with a simple logical AND operation like this:

int bit_7_is_set = result & (1U << 7);  // a.k.a. 128

If the result of the AND operation is non-zero (it will either be 0 or 128 in the above case), the corresponding bit is set in the result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top