Quote:

> Hi there,

> I'm reading K&R2, and up to Bitwise Operators right now. It said that

> bitwise AND operator & is often used to mask off some set of bits (And

> that's what i've learnt from Assembly) .

> It had an example like this:

> n = n & 0177;

(...which is analogous to the general assignment form X = X OP Y, i.e.

perform the operation Y on X, storing the result in X... sorry if you

already knew that...)

Quote:

> it said this'll sets to zero all but the low-order 7 bits of n.

0177 is an octal representation. In octal, each octit (!) represents three

bits. This is because it takes three bits to represent the number 7, which

is the highest octit commonly accepted to be valid. Since in 0177 we have

two 7s at the end, we can see that the lowest six bits are set, and the 1

makes the seventh. Here's a picture:

0 1 7 7 octal =

000 001 111 111 binary

Now for the AND operation, &. Single & is a bitwise operation (as opposed

to && which is a logical operation).

Here's the truth table for AND:

A B A & B

0 0 0

0 1 0

1 0 0

1 1 1

So A & B is only 1 if both A and B are 1. Now let's look at some random bit

pattern n:

n 0111010101010101110101

0177 0000000000000001111111

n & 0177 0000000000000001110101

Now let's consider what's happening here. Because the high-order bits of

0177 are all zero, all the corresponding bits in the result must be zero

too, because (in the AND truth table, any row which has zero in either of A

and B also has a zero in A & B.

So we need only look at the bottom 7 bits of n. Those which are set (i.e.

1) remain 1 in the result, and those which aren't, don't. Hence, the bits

in which we are not interested can be said to have been masked off, with

0177 being the 'mask'.

Quote:

> and it said :

> x = x | SET_ON;

> sets to one in x the bits that are set to one in SET_ON.

> Does it means SET_ON has been declared as a variable or a symbolic

constant

> which is 1 in value?

No. SET_ON is a mask again. This time it's for switching bits on, not off.

Let's assume this, just for the sake of argument:

#define SET_ON 0177

Now apply exactly the same method as before, except that we're using OR

instead of AND:

A B A | B

0 0 0

0 1 1

1 0 1

1 1 1

Quote:

> Lastly, I want to ask. If a variable set to have a value of 0. Does it

> equals to NULL? since NULL == 0.

Think of NULL as 'the invalid pointer value'. It's a value you give to

pointers when you want them to be detectably invalid later.

From your source code's point of view, if you use 0 when you mean NULL,

it'll be converted for you. If you use NULL when you mean 0, you might get

a warning, and it's considered bad practice anyway.

If you are using pointers, use NULL.

If you are using anything else, use 0.

--

Richard Heathfield

"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.

comp.lang.c FAQ: http://www.eskimo.com/~scs/C-faq/top.html