Does anyone understand this stuff i can count strait up in hex and i know the binary number system from my cisco class pretty well. But i dont understand how to use hex as flags and i really dont understand the pupose or bitwise operators i know what they do but why use them?
When you're doing:
if(flag){}
you're really checking if the flag variable is non-zero, upon which the if statement is executed.
This is equivalent to the following statement:
if( flag != 0 )
In C, true and false are defined as:
#define TRUE 1
#define FALSE 0
whereas there is a defined type Boolean
typedef int Boolean;
Bitwise operators are used for accessing certain bits in a numerical entity. It's used in different areas, some of them being areas where you need to access only a certain bit (hardware registers), or bit per bit accessing a file format structure, or transformation of input data, or for example conversion from big endian to little endian format.
Ofcourse, there are millions of instances where you use bitwise operations, so I suggest you get a hang of it pretty soon
Say, you have a longword (32bits) and you only want the lowest 8 bits (byte). Look at this C snippet showing the & (AND) operator:
long a = 0xBAADF00D;
unsigned char b;
b = a & 0xFF; // 0x000000FF
Variable b will now contain 0x0D.
>> is the bitwise shift right operator. It will shift the bitmask as many positions as you want to the right. << does the same to the left.
b = (a & 0xFF0000) >> 16;
will give b the value 0xAD. First the paranthesis will result in 0x00AD0000 and then the shift to right will result in 0x000000AD.
<< and >> also have the effect of multiplying or diving by the power of 2 multiples.
a = 6;
a = a << 1; // times 2
a equals now 12;
a= 5;
a = a << 2; // times 4
a equals now 20.
a = 16;
a = a >> 3; // divided by 8
a equals 2.
the | (OR) operator is used for setting bits (AND was used for clearing bits):
unsigned int a = 0xFF00;
a = a | 0xAC;
a equals now 0xFFAC.
Bits that are already set, remain set.
The ~ (NOT) operator isused to reverse the bits from zero to 1 and viceversa.
a = 0x00FF00FF;
a = ~a
a equals 0xFF00FF00.
Let me see if you understood these things...
What is the value of a after these statements:
long a = 0x55AA55AA;
long b = 0xBAADF00D;
a = (a & b) | (~a >> 16);
Hope I haven't been a pain in the ass