I want a simple C function which will return true if the n-th bit in a byte is set to1. Otherwise it will return false.
This is a critical function in terms of execution time, so I am thinking of the most optimal way to do that.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The following function can do what you need:
This assumes 8-bit bytes (not a given in C) and the zeroth bit being the highest order one. If those assumption are incorrect, it simply comes down to expanding and/or re-ordering the
maskarray.No error checking is done since you cited speed as the most important consideration. Do not pass in an invalid
n, that’ll be undefined behaviour.At insane optimisation level
-O3, gcc gives us:which is pretty small and efficient. And if you make it static and suggest inlining, or force it inline as a macro definition, you can even bypass the cost of a function call.
Just make sure you benchmark any solution you’re given, including this one (a). The number one mantra in optimisation is “Measure, don’t guess!”
If you want to know how the bitwise operators work, see here. The simplified AND-only version is below.
The AND operation
&will set a bit in the target only if both bits are set in the tewo sources. The relevant table is:For a given
charvalue, we use the single-bit bit masks to check if a bit is set. Let’s say you have the value 13 and you want to see if the third-from-least-significant bit is set.You can see that all the zero bits in the mask result in the equivalent result bits being zero. The single one bit in the mask will basically let the equivalent bit in the value flow through to the result. The result is then zero if the bit we’re checking was zero, or non-zero if it was one.
That’s where the expression in the
returnstatement comes from. The values in themasklookup table are all the single-bit masks:(a) I know how good I am, but you don’t 🙂