Search code examples
arraysbit-manipulationbitwise-operatorsbit-shiftbitflags

Bitstrings and flag shifting


I'm pretty new to bitwise and all the fun jazz and so don't quite understand everything about it. I have two questions.

A) A flags and bitshift question

I recently ran across something similar to below

if (flags & (1 << 3)) {
    function_A();
}

I can see is is an AND operator and a left bit shift, however I am unsure what the flag does and its purpose (to my understanding its a collection of booleans to save space), when I usually come across left shifts, it is something such as 10100101 << 3, which would be 00101000 (I believe), but that does not seem to be the case here. So what exactly are the conditions under which the above function would be called?

B) Also a flags question (related to the first due to the nature of it).

TCPs contain packets which consist of 1 bit flags in byte 13.There is a bit of byte 13 (bit 1 i believe) which is the SYN flag to request a connection. To "request a connection" how exactly would you call that bit assuming you can access it assuming its stored in some sort of array and is accessed VIA packetNO[13]. Would it be similar to below?

if (packetNO[13] & (1 << 2)) {
}

the above checking if a connection has been requested, by shifting a true bit to position 2 (bit 1?)

Please explain these concepts to me and provide examples to assist if possible, I am unsure if I am correct or not.


Solution

  • The and operator is such its output is at one only if both operands are at 1. Hence

    if(f & 1) { ... }
    

    tests is the least significant bit of f is set.

    If you want to test if another bit is set, there are two ways to do that.

    1. use the bitwise shift operator << that will shift its operand by a given amount. For instance, to test if the third bit (or bit #2 counting from lsb) is set, you an use 1<<2. This will result to a number equal to 000..00100 and by anding, this will check if the corresponding bit is set.
    if(f & (0x1<<2)) { ... }
    
    1. Alternatively, you can use hexadecimal numbers do describe the bit pattern that you want to test. The same test can done by using 0x4 as the binary code of 4 is 000..0100
    if(f & 0x4) { ... }
    

    It is up to you to determine which one is more readable.

    So, the first test in your question checks if fourth bit of flag (bit #3) is set and the second one tests if bit #1 of packect[13] is set.