Octal, Hexadecimal and Binary Numbers and Bitwise Operations

Tom Lehrer's "New Math" — introduction to octal arithmetic.  Note:  C was initially developed on a PDP-11 computer, which used octal numbers to report bit patterns.

C's rules for representing decimal, octal, and hexadecimal numbers in constants.
    A field of digits beginning with a non-zero digit is a decimal number
    A field beginning with "0x" is a hexadecimal number.  The following characters are 0-9 and a-f .  "0X" and A-F are also allowed.
    Otherwise a field beginning with 0 is an octal number.  The following characters are 0-7.

Connection between octal numbers, hexadecimal numbers and binary numbers:
In an octal number, each digit represents three bits in the binary number, 0 for "000" up through 7 for "111".
In a hexadecimal number, each digit represents four bits in the binary number, 0 for "0000" up through F for "1111".  The digits are referred to as nibbles 2 nibbles to a byte.

In a binary number, the bits are numbered from zero (the least significant bit) to (size-1), the most significant bit.  This is also the sign bit for an integer (unless it has been expressly declared as unsigned).

Drill program on conversion of decimal numbers to binary, octal, and hexadecimal.  Reports the octal and hex and pauses before showing the binary.
binary_out.txt   binary_out.c   binary_out.exe

There is a unary binary operator, the ~.  It has the same precedence and associativity as the other unary operators (just under parentheses and square brackets).  Its effect is to invert every bit in its operand.

There are two bitwise shift operators, where the left operand is the number being modified and the right operand is the size of the shift.  Their precedence is below arithmetic operators and above comparison operators.

The other bitwise operators have precedence between the comparison operators (< > etc.) and the boolean/logical operators (&& and ||).  They require integers operands.  Typically one operand is the number being examined and the other operand is a "mask", a bit pattern for modifying that number.  In order of descending precedence the bitwise operators are:

Students who go on to the Operating Systems course will see a lot more of this stuff.

Enrichment Material

Conversion of user input with scanf

Output of octal and hexadecimal numbers with printf:  the bare %o and %x print the number without the leading zero or "0x".
To force that output,. one must use the specification %#o and %#x — the "#" flag specifies that 'the value should be converted to an "alternate form"'. [Linux man page on fprintf]