Bitwise operators

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • den2k

    #16
    Re: Bitwise operators

    On 19 Giu, 08:35, rahul <rahulsin...@gm ail.comwrote:
    On Jun 19, 2:32 am, Santhosh <santhoshvenkat 1...@gmail.comw rote:
    >
    Hi to all,
    How the individual digits of a number can be obtained using the
    bitwise operators alone.Is it possible to do it ?
    I do not think it is possible using only bitwise operators because
    they work on a base-2 numbering system whereas you want to know the
    _decimal_ digits.

    Comment

    • Richard Heathfield

      #17
      Re: Bitwise operators

      den2k said:
      On 19 Giu, 08:35, rahul <rahulsin...@gm ail.comwrote:
      >On Jun 19, 2:32 am, Santhosh <santhoshvenkat 1...@gmail.comw rote:
      >>
      Hi to all,
      How the individual digits of a number can be obtained using the
      bitwise operators alone.Is it possible to do it ?
      >
      I do not think it is possible using only bitwise operators because
      they work on a base-2 numbering system whereas you want to know the
      _decimal_ digits.
      We have already discussed the fact that addition can be done using the ^,
      &, and << operators (XOR for add-without-carry, AND and LSH for obtaining
      and moving the carry, repeat until no carry). Given addition, subtraction
      is easy - simply take two's complement and add.

      Given subtraction, division becomes not only possible but even easy.
      Consider 34 / 10 (which we need to do if we're going to get the result 3
      and remainder 4). 34 is 100010 in binary, and ten is 1010. Observe long
      division in binary, noting that subtraction is done with ^ & << and the
      two's complement, comparison can be done by subtraction, isolating the
      bits necessary for the trial divisions can be done using shift and AND,
      and "bringing down a bit" can be done with shift and OR:

      1010)100010
      1010 <---- Subtrahend <= minuend? No.

      _0000
      1010)100010
      1010 <---- Subtrahend <= minuend? Yes. Subtract.

      _00001
      1010)100010
      1010
      ---
      111 <----- bring down a bit

      _00001
      1010)100010
      1010
      ---
      1110
      1010 <---- Subtrahend <= minuend? Yes. Subtract.

      _000011 <---- Result: 3
      1010)100010
      1010
      ---
      1110
      1010
      ---
      100 <---- Remainder: 4

      Yes, Virginia, you *can* divide by ten, even if you're thinking in binary.

      --
      Richard Heathfield <http://www.cpax.org.uk >
      Email: -http://www. +rjh@
      Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
      "Usenet is a strange place" - dmr 29 July 1999

      Comment

      Working...