Nano HE Nano HE - 3 years ago 379
C Question

Bit Operation in C / C++

When we talk Bit Operation in C or C++.
Does bit start from bit0 or bit1 ? Which one is more make sense?
As I know A bit can assume either of two values: 1 or 0.

Answer Source

Generally, bit identifiers start from 0 at the least significant end, such as with the following octet:

+----+----+----+----+----+----+----+----+
| b7 | b6 | b5 | b4 | b3 | b2 | b1 | b0 |
+----+----+----+----+----+----+----+----+
  80   40   20   10   08   04   02   01    <-- hex value

While a bit can take either a 0 or 1 value, that doesn't limit their identifiers, which can range from zero up to the number of bits minus 1.

For an explanation of the bitwise operators, see here.

For example, if you wanted to know whether b3 was set in C:

b3 = value & 0x08; // non-zero if set.

Similarly, setting b0 and clearing b7 can be done with:

value = (value | 0x01) & 0x7f; // or with 0000-0001, and with 0111-1111.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download