C Program#159 – To represent Decimal number into Binary (bits).

Program to represent Decimal number into Binary (bits).:

Brief Intro : AND Masking

  • Bitwise AND (&) operator is used to check whether a particular bit in a number is ON(1) or OFF(0).
  • Second Operand in Bitwise AND (&) operation is generally called AND MASK, since it masks (covers) the bits of the first operand and gives resultant bit series, which may be used to check particular bit’s status.
  • Thus, Second Operand’s selection based upon the particular bit number to be checked in the first operand. Such as –
    • If first operand have bits like – 0100 0001 (Decimal = 65)
    • Bits are numbered from Right to Left starting from Zero.
    • Thus, in 65 (0100 0001), 0th and 6th bit is ON (1), while 1st, 2nd, 3rd, 4th, 5th & 7th bit is OFF(0).
    • Now, suppose we want to check 6th bit is OFF(0) or ON(1),
    • Then, we must use a number as Second Operand, whose only that particular bit, 6th bit is already ON (1), such as – 0100 0000 (Decimal = 64)

    • If AND Operand results in a Non-Zero value (i.e. Same number, Second Operand), it means bit is ON(1).
    • Otherwise the result will be Zero means OFF(0).
      1. Example:

      2.  65 = 0100 0001 (First Operand)
      3. &64 = 0100 0000 (Second Operand – AND MASK)
      4. =64 = 0100 0000 (Result -Same number as Second Operand mean 6th bit is ON (1).
  • Still not understood ? See the proper working example in action below.

Program Logic : Binary Representation of Decimal Number.

  • Take input of a Decimal Number.
  • Check all bits using AND (&) Operation using loop to check whether they are ON (1) or OFF (0).
  • Since Integer is assumed here as 32 Bits long, that means 31 to 0 all numbers must be used as AND MASK.
  • In each iteration, check if AND (&) Operation results in 0 then print 0, otherwise print 1.
  • To count total number of ON (1) and OFF(0) Bits, add counter for both and increment them in every iteration in concerned block.
  • Still not understood ? See the proper working example in action below.

Full Well Commented, Self-Explanatory Example Program of the same given below.

Below Here is the Output of the program.

Output of the Program :