Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this condition test?

Tags:

c

objective-c

Came across this conditional in some uncommented Objective-C code:

if (w & (w - 1))
{
    i = 1;
    while (i < w)
    {
        i *= 2;
    }
    w = i;
}

Where w is a size_t greater than 1.

Update: Added the code contained by the conditional for context.

like image 321
Shaun Inman Avatar asked Jan 04 '10 16:01

Shaun Inman


People also ask

What are test conditions with example?

Test Conditions. Test conditions are the constraints that you should follow to test an application. Example: When User Name and Password are valid then application will move forward. Test conditions can be a piece of functionality or anything you want to verify.

What is a test condition quizlet?

A set of conditions and/or variables under which a tester will determine if a requirement upon an application is satisfied. What does a Test Case include during the planning phase? -Test case ID.

What is a test condition in Java?

Test Cases are the conditions that are to be tested when the software is created. Before writing test cases in Java, we need to understand what test cases are. This section will cover a brief introduction of Test cases and then how we can write test cases in Java.


2 Answers

It tests whether more than one bit is set in w, i.e. whether it's not an exact power of two. See here.

like image 173
unwind Avatar answered Sep 25 '22 20:09

unwind


It seems it's checking for powers of two. If w is a power of 2, the bit representation of w and w-1 have no bit in common set to 1. Example : 100 for 4 and 011 for 3. Thus the bitwise and (& in C) will give false for any w which is a power of two.

like image 41
glmxndr Avatar answered Sep 26 '22 20:09

glmxndr