Why bitwise operators?

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

    Why bitwise operators?


    Why would one use bitwise operators? I can program in various languages in
    some shape or form (C++, PHP, some scripting) and I've heard/seen bitwise
    operators before, but never understood why anyone would use them - any real
    world examples or ideas? Examples follow (that I am reading in my Core
    JavaScript Guide 1.5).

    15 & 9 yields 9 (1111 & 1001 = 1001)
    15 | 9 yields 15 (1111 | 1001 = 1111)
    15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
    in addition there are AND,OR,XOR,NOT and left and right shifts which would
    only extend this post longer than nescessary...

    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is top-posting such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet?


  • Lasse Reichstein Nielsen

    #2
    Re: Why bitwise operators?

    "Randell D." <you.can.email. me.at.randelld@ yahoo.com> writes:
    [color=blue]
    > Why would one use bitwise operators?[/color]

    I would say that it should rarely be needed.

    In C, you often had to fiddle with bits, since you did most
    I/O-programming directly on the bits. You had to toggle bits
    and implement your own bit vectors. It made perfect senst
    to have bit-operations in such a low-level language.

    In Javascript, you can implement a bit vector as an integer and use
    bitwise operators. You could also make it an array of booleans and
    create the methods you need. The latter scales better.

    There are still cases, where integer arithmetic can more easily, or
    just faster, be implemented with bitwise operations. I know there are,
    I just can't remember any of them right now.

    /L
    --
    Lasse Reichstein Nielsen - lrn@hotpop.com
    Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
    'Faith without judgement merely degrades the spirit divine.'

    Comment

    • Jeff North

      #3
      Re: Why bitwise operators?

      On Wed, 01 Oct 2003 22:18:53 GMT, in comp.lang.javas cript "Randell D."
      <you.can.email. me.at.randelld@ yahoo.com> wrote:
      [color=blue]
      >|
      >| Why would one use bitwise operators? I can program in various languages in
      >| some shape or form (C++, PHP, some scripting) and I've heard/seen bitwise
      >| operators before, but never understood why anyone would use them - any real
      >| world examples or ideas? Examples follow (that I am reading in my Core
      >| JavaScript Guide 1.5).
      >|
      >| 15 & 9 yields 9 (1111 & 1001 = 1001)
      >| 15 | 9 yields 15 (1111 | 1001 = 1111)
      >| 15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
      >| in addition there are AND,OR,XOR,NOT and left and right shifts which would
      >| only extend this post longer than nescessary...[/color]

      I've just recently used such an example. I needed to set up some form
      of security for different people accessing different web pages.
      Instead of maintaining 12+ variables; I bitmapped the values into a
      single variable. Now all I need to do is place some code like:
      if( security_bits & CONST_dept_name )
      and process from there.

      I could also use
      if( security_bits & (CONST_dnm1 + CONST_dnm2 + CONST_dnm3) )

      This is server-side scripting. I can't see much benefit in using this
      client-side.
      ---------------------------------------------------------------
      jnorth@yourpant sbigpond.net.au : Remove your pants to reply
      ---------------------------------------------------------------

      Comment

      • Randell D.

        #4
        Re: Why bitwise operators?


        "Lasse Reichstein Nielsen" <lrn@hotpop.com > wrote in message
        news:7k3ojs4i.f sf@hotpop.com.. .[color=blue]
        > "Randell D." <you.can.email. me.at.randelld@ yahoo.com> writes:
        >[color=green]
        > > Why would one use bitwise operators?[/color]
        >
        > I would say that it should rarely be needed.
        >
        > In C, you often had to fiddle with bits, since you did most
        > I/O-programming directly on the bits. You had to toggle bits
        > and implement your own bit vectors. It made perfect senst
        > to have bit-operations in such a low-level language.
        >
        > In Javascript, you can implement a bit vector as an integer and use
        > bitwise operators. You could also make it an array of booleans and
        > create the methods you need. The latter scales better.
        >
        > There are still cases, where integer arithmetic can more easily, or
        > just faster, be implemented with bitwise operations. I know there are,
        > I just can't remember any of them right now.
        >
        > /L
        > --
        > Lasse Reichstein Nielsen - lrn@hotpop.com
        > Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
        > 'Faith without judgement merely degrades the spirit divine.'[/color]

        I'm glad its a rarely used facility/function... I'm pretty sure I can get
        along with javascript without it so that suites me fine.

        Cheers
        randell d.


        Comment

        • Richard Cornford

          #5
          Re: Why bitwise operators?

          "Lasse Reichstein Nielsen" <lrn@hotpop.com > wrote in message
          news:7k3ojs4i.f sf@hotpop.com.. .[color=blue]
          >"Randell D." <you.can.email. me.at.randelld@ yahoo.com> writes:
          >[color=green]
          >> Why would one use bitwise operators?[/color]
          >
          >I would say that it should rarely be needed.
          >
          >In C, you often had to fiddle with bits, since you did most
          >I/O-programming directly on the bits. You had to toggle bits
          >and implement your own bit vectors. It made perfect senst
          >to have bit-operations in such a low-level language.[/color]

          The bitwise operators are available at the very low level of CPU
          instructions which means that they are almost trivial to implement in
          any language. It might be as much that as anything else that has them
          finding their way into ECMA Script.

          <snip>[color=blue]
          >There are still cases, where integer arithmetic can more
          >easily, or just faster, be implemented with bitwise operations.
          >I know there are, I just can't remember any of them right now.[/color]

          One application is integer division and multiplication by 2, 4, 8,.. etc
          using the shift operators. I recently used - x = y >> 1 - as a division
          by 2 with a floored result, though it is not the same as - x =
          Math.floor(y/2) -, and it looks like I had rendered the entire
          process unnecessary by the final version of that code.

          Shift is also useful for splitting hex representations of RGB colors
          (used because they translate easily from HTML and CSS) into their
          component colors. That could be combined with bitwise AND to mask out
          unwanted parts of a number (the alternative being y%256):-

          var nRGBin = 0xFB3E1C;
          var nR=(nRGBin>>16) & 0xFF;
          var nG=(nRGBin>>8) & 0xFF;
          var nB=nRGBin & 0xFF;

          Richard.


          Comment

          • VK

            #6
            Re: Why bitwise operators?

            As it said, bitwises are low level, so they go right through the
            interpreter's vertebral, not touching its brains :-) So they are quick.

            When I programmed EdLine (JavaScript-based text editor), I had some ugly
            switches with about 30 cases in each for keyboard input. On a slow machine
            it moved like an old god. Then I used bitwises instead to sort keycodes by
            byte structure, and it run like a young poppy.

            Talking about rarely used features: how long ago did you last time use
            Math.acos() or Math.atan() ? :-)



            Randell D. <you.can.email. me.at.randelld@ yahoo.com> wrote in message
            news:hpIeb.1632 $pl3.1428@pd7tw 3no...[color=blue]
            >
            > Why would one use bitwise operators? I can program in various languages[/color]
            in[color=blue]
            > some shape or form (C++, PHP, some scripting) and I've heard/seen bitwise
            > operators before, but never understood why anyone would use them - any[/color]
            real[color=blue]
            > world examples or ideas? Examples follow (that I am reading in my Core
            > JavaScript Guide 1.5).
            >
            > 15 & 9 yields 9 (1111 & 1001 = 1001)
            > 15 | 9 yields 15 (1111 | 1001 = 1111)
            > 15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
            > in addition there are AND,OR,XOR,NOT and left and right shifts which would
            > only extend this post longer than nescessary...
            >
            > --
            > A: Because it messes up the order in which people normally read text.
            > Q: Why is top-posting such a bad thing?
            > A: Top-posting.
            > Q: What is the most annoying thing on usenet?
            >
            >[/color]


            Comment

            • Bryan Field-Elliot

              #7
              Re: Why bitwise operators?

              Randell D. wrote:[color=blue]
              > Why would one use bitwise operators? I can program in various languages in
              > some shape or form (C++, PHP, some scripting) and I've heard/seen bitwise
              > operators before, but never understood why anyone would use them - any real
              > world examples or ideas? Examples follow (that I am reading in my Core
              > JavaScript Guide 1.5).
              >
              > 15 & 9 yields 9 (1111 & 1001 = 1001)
              > 15 | 9 yields 15 (1111 | 1001 = 1111)
              > 15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
              > in addition there are AND,OR,XOR,NOT and left and right shifts which would
              > only extend this post longer than nescessary...
              >[/color]

              Their usefulness is very limited from a Javascript perspective; however
              they do come in very handy once in a blue moon. One example is color
              manipulation, I've used Javascript to take color settings from the
              server, and brighten them up a bit... For example if a color code is in
              the variable "color", then this will brigthen it by raising the high bit
              of each color component (R, G, B):

              color |= 0x808080;

              (it's been a while but I'm pretty sure that was how we did it).



              --

              Bryan Field-Elliot


              Comment

              • asdf asdf

                #8
                Re: Why bitwise operators?

                Yeah but what if you want to write a javascript NIM player ????????


                :)

                Comment

                • Anthony Buckland

                  #9
                  Re: Why bitwise operators?

                  Randell D. wrote:
                  [color=blue]
                  >Why would one use bitwise operators? I can program in various languages in
                  >some shape or form (C++, PHP, some scripting) and I've heard/seen bitwise
                  >operators before, but never understood why anyone would use them ...
                  >[/color]

                  There was a time -- coincidentally, the time during which I did my heaviest
                  duty software development (I'm retired now) -- when people actually cared
                  about how much room things took. Bitwise manipulation was essential
                  to using single bits in a byte to indicate different conditions,
                  preferences,
                  etc. For all I know to the contrary, this may still be important in
                  applications like cellphones and other smart appliances. It would certainly
                  be important to recovering data from older databases and in retaining
                  upwards compatability for older applications.

                  Comment

                  • Jim Morrison

                    #10
                    Re: Why bitwise operators?



                    Randell D. wrote:
                    [color=blue]
                    >Why would one use bitwise operators? I can program in various languages in
                    >some shape or form (C++, PHP, some scripting) and I've heard/seen bitwise
                    >operators before, but never understood why anyone would use them - any real
                    >world examples or ideas? Examples follow (that I am reading in my Core
                    >JavaScript Guide 1.5).
                    >
                    >15 & 9 yields 9 (1111 & 1001 = 1001)
                    >15 | 9 yields 15 (1111 | 1001 = 1111)
                    >15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
                    >in addition there are AND,OR,XOR,NOT and left and right shifts which would
                    >only extend this post longer than nescessary...
                    >[/color]

                    Here is a real word example:

                    The IP address called 10.0.0.1 is

                    (10 * 1<<24) + (0 * 1<<16) + (0 * 1<<8) + 1 = 167772161




                    Jim

                    [color=blue]
                    >
                    >
                    >[/color]

                    Comment

                    • Steve van Dongen

                      #11
                      Re: Why bitwise operators?

                      On Fri, 03 Oct 2003 03:27:59 GMT, Jim Morrison <dorz11@comcast .net>
                      wrote:
                      [color=blue]
                      >
                      >
                      >Randell D. wrote:
                      >[color=green]
                      >>Why would one use bitwise operators? I can program in various languages in
                      >>some shape or form (C++, PHP, some scripting) and I've heard/seen bitwise
                      >>operators before, but never understood why anyone would use them - any real
                      >>world examples or ideas? Examples follow (that I am reading in my Core
                      >>JavaScript Guide 1.5).
                      >>
                      >>15 & 9 yields 9 (1111 & 1001 = 1001)
                      >>15 | 9 yields 15 (1111 | 1001 = 1111)
                      >>15 ^ 9 yields 6 (1111 ^ 1001 = 0110)
                      >>in addition there are AND,OR,XOR,NOT and left and right shifts which would
                      >>only extend this post longer than nescessary...[/color][/color]

                      I'm sure there's a whole lot of things of questionable usefulness that
                      you can do with bit operations. Here's one... Swapping the contents
                      of two variables without using a temp variable.

                      var a = 15;
                      var b = 28;
                      a ^= b; // a = a XOR b
                      b ^= a; // b = b XOR a
                      a ^= b; // a = a XOR b

                      With memory as abundant as it is these days, I doubt people would do
                      something like that any more.

                      Randall's example is more interesting because it shows that a<<b is
                      equivalent to a * Math.pow(2, b). As someone already said, bit shifts
                      are a very simple operation and will be faster than multiplying or
                      dividing by multiples of 2.
                      [color=blue]
                      >Here is a real world example:
                      >
                      >The IP address called 10.0.0.1 is
                      >
                      >(10 * 1<<24) + (0 * 1<<16) + (0 * 1<<8) + 1 = 167772161[/color]

                      Continuing with the real world IP example, there's the method for
                      determining the network id portion of the ip address.

                      IP Address. . . . . . . . . . . . : 192.168.3.2
                      Subnet Mask . . . . . . . . . . . : 255.255.254.0

                      192.168.3.2 == 11000000 10101000 00000011 00000010
                      255.255.254 == 11111111 11111111 11111110 00000000

                      Network ID = IP Address & Subnet Mask
                      = 11000000 10101000 00000010 00000000
                      = 192.168.2.0

                      Regards,
                      Steve

                      Comment

                      • Richard Cornford

                        #12
                        Re: Why bitwise operators?

                        "Steve van Dongen" <stevevd@hotmai l.com> wrote in message
                        news:rbhqnv84a7 iei7fjmi8eiv2j6 u2qce2m8a@4ax.c om...
                        <snip>[color=blue]
                        >Randall's example is more interesting because it shows that
                        >a<<b is equivalent to a * Math.pow(2, b). As someone already
                        >said, bit shifts are a very simple operation and will be
                        >faster than multiplying or dividing by multiples of 2.[/color]
                        <snip>

                        The obvious next question is; if faster then by how much? So I created
                        some test pages to find out.

                        Comparing - Math.floor(S/2) - with - (S>>1) - seemed a reasonable
                        starting point. There are some differences as Math.floor rounds negative
                        numbers downwards while the shift moves them towards zero and the result
                        of the shift is a 32 bit signed integer so it cannot represent the same
                        integer range as the IEEE float that Math.floor outputs. The test page
                        is:-

                        <URL: http://www.litotes.demon.co.uk/js_speed/intDivBy2.html >

                        - and produced the results (taking Math.floor(S/2) as 100% on all tested
                        browsers for comparison):-

                        Net 4 Opera 7.11 IE 6 Mozilla 1.3 Konqu 3.1
                        Math.floor(n/2) -- -- 100% -- --
                        (n>>1) 7.18% 22.94% 8.60% 16.28% 16.93%

                        Making the shift operation between 4 and 14 times faster.

                        That seemed a reasonable start so I compared - Math.floor(n)*2 - and -
                        (n<<1) :-

                        <URL: http://www.litotes.demon.co.uk/js_speed/intMulBy2.html >

                        - getting the results:-

                        Net 4 Opera 7.11 IE 6 Mozilla 1.3 Konqu 3.1
                        Math.floor(n)*2 -- -- 100% -- --
                        (n<<1) 8.03% 21.82% 8.46% 26.19% 26.80%

                        Generally worse but not by much.

                        Looking at the above tests it occurred to me that any bitwise operator
                        was going to have the a similar effect to Math.floor (when the internal
                        ToInt32 function is called) if its input was a positive integer <= 31
                        bits, as might be the case when calculating screen co-ordinates with
                        floats and then converting the results to pixel co-ordinates. So any
                        bitwise operation that would not alter a 32 bit integer may be
                        substituted for Math.floor for those cases:-

                        <URL: http://www.litotes.demon.co.uk/js_sp...orMethods.html >

                        Net 4 Opera 7.11 IE 6 Mozilla 1.3 Konqu 3.1
                        Math.floor(n) -- -- 100% -- --
                        (n&0xFFFFFFFF) 14.40% 29.54% 14.42% 52.03% 24.25%
                        (n<<1)>>1 10.97% 56.04% 19.86% 39.70% 43.49%
                        (n|0) 8.23% 29.02% 10.64% 33.84% 24.33%

                        The double shift did not strike me as a good candidate as it further
                        reduces the maximum size of the integer (and involves two operations)
                        but as it performed generally badly it can be dismissed for that reason
                        alone (though I was surprised that it outperformed bitwise AND on
                        Mozilla 1.2). The bitwise OR zero operation is the clear winner at
                        between 3 and 12 times faster than Math.floor. Not a complete substitute
                        but if enough is known about the input it could be a fast alternative in
                        some cases.

                        Richard.


                        Comment

                        Working...