how to specify power of number

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

    how to specify power of number

    Hi, I'm new to c, so please excuse, if this is silly ;-)

    I made a C function, which takes IP adress from string and converts to unsigned long int. Everything
    works, but I found that the "counting" part part works only with this:

    numericip=atoi( textip[0])*256*256*256+a toi(textip[1])*256*256+atoi( textip[2])*256+atoi(text ip[3]);

    When I wrote *(256^3), I got fake results. I'd like to use something more sophisticated, instead of 256*256
    *256, which does look silly ;-) (Just curious, what if I'd ever need to make 100th power of 256 ;-) )

    Thank you in advance.
  • Ben Bacarisse

    #2
    Re: how to specify power of number

    Yanb <Yanb@whatever. invalidwrites:
    Hi, I'm new to c, so please excuse, if this is silly ;-)
    Well, not silly, but I am surprised that you start a new language
    without consulting some sort of reference.
    I made a C function, which takes IP adress from string and converts to unsigned long int. Everything
    works, but I found that the "counting" part part works only with this:
    >
    numericip=atoi( textip[0])*256*256*256+a toi(textip[1])*256*256+atoi( textip[2])*256+atoi(text ip[3]);
    >
    When I wrote *(256^3), I got fake results. I'd like to use something
    more sophisticated, instead of 256*256
    ^ is exclusive or in C. C does not have an exponentiation operator.
    Most C programmers would use a shift (<<) by 24, 16 or 8 bits to
    compute the value you want.

    --
    Ben.

    Comment

    • Bartc

      #3
      Re: how to specify power of number


      "Yanb" <Yanb@whatever. invalidwrote in message
      news:fu9q89$kem $1@aioe.org...
      Hi, I'm new to c, so please excuse, if this is silly ;-)
      >
      I made a C function, which takes IP adress from string and converts to
      unsigned long int. Everything
      works, but I found that the "counting" part part works only with this:
      >
      numericip=atoi( textip[0])*256*256*256+a toi(textip[1])*256*256+atoi( textip[2])*256+atoi(text ip[3]);
      >
      When I wrote *(256^3), I got fake results. I'd like to use something more
      sophisticated, instead of 256*256
      *256, which does look silly ;-) (Just curious, what if I'd ever need to
      make 100th power of 256 ;-) )
      You would have to use pow(256,3) which uses floating point arithmetic -- not
      recommended, even though the compiler is likely to optimise.

      Your code is fine as it is, the compiler will optimise 256*256*256 to
      *16777216 or <<24. Or just write those in yourself.

      --
      Bart


      Comment

      • Antoninus Twink

        #4
        Re: how to specify power of number

        On 18 Apr 2008 at 11:01, Bartc wrote:
        You would have to use pow(256,3) which uses floating point arithmetic -- not
        recommended, even though the compiler is likely to optimise.
        >
        Your code is fine as it is, the compiler will optimise 256*256*256 to
        *16777216 or <<24. Or just write those in yourself.
        For general integer powers, a simple square-and-multiply algorithm is a
        good bet, e.g.

        unsigned long long power(unsigned a, unsigned b)
        {
        unsigned long long r, bit, pow;
        for(bit=r=1, pow=a; bit<=b; bit<<=1, pow *= pow)
        if(b & bit)
        r*=pow;
        return r;
        }

        The hardest part is checking for overflow - left as an exercise for the
        reader...

        Comment

        • Yanb

          #5
          Re: how to specify power of number

          Ben Bacarisse <ben.usenet@bsb .me.ukwrote in
          news:87od877aoh .fsf@bsb.me.uk:
          Yanb <Yanb@whatever. invalidwrites:
          >
          >Hi, I'm new to c, so please excuse, if this is silly ;-)
          >
          Well, not silly, but I am surprised that you start a new language
          without consulting some sort of reference.
          Hi, and thank you for reply. I have read some very basics, but usually I need a language for a specific
          thing and as soon as I know enough to complete the task, I leave learning till later :-/

          Do you have some tip for a newbie where to start? Of course I can google out load of pages about c,
          but no search engine can compete with reference from a human ;-)
          >
          >I made a C function, which takes IP adress from string and converts
          >to unsigned long int. Everything works, but I found that the
          >"counting" part part works only with this:
          >>
          >numericip=atoi (textip[0])*256*256*256+a toi(textip[1])*256*256+atoi( tex
          >tip[2])*256+atoi(text ip[3]);
          >>
          >When I wrote *(256^3), I got fake results. I'd like to use something
          >more sophisticated, instead of 256*256
          >
          ^ is exclusive or in C. C does not have an exponentiation operator.
          Most C programmers would use a shift (<<) by 24, 16 or 8 bits to
          compute the value you want.
          >
          Oh yes, that's it, thanks, shifting I know shifts from php ;-) This way will need less cpu cycles than
          multiplication.

          Ok, so there no way to write mathematic "power of" in c?

          Comment

          • Jens Thoms Toerring

            #6
            Re: how to specify power of number


            Yanb <Yanb@whatever. invalidwrote:
            Ben Bacarisse <ben.usenet@bsb .me.ukwrote in
            news:87od877aoh .fsf@bsb.me.uk:
            ^ is exclusive or in C. C does not have an exponentiation operator.
            Most C programmers would use a shift (<<) by 24, 16 or 8 bits to
            compute the value you want.
            Oh yes, that's it, thanks, shifting I know shifts from php ;-) This way
            will need less cpu cycles than multiplication.
            I wouldn't bet on that, a good compiler probably will "see" if
            a multiplication can be replaced by a shift operation and will
            use that if it's faster on the machine you're compiling for.
            Ok, so there no way to write mathematic "power of" in c?
            While there's no "power of" operator like for example in FORTRAN
            there's the pow() function from the math part of the standard
            C library, but which takes double arguments and returns a double.

            Regards, Jens
            --
            \ Jens Thoms Toerring ___ jt@toerring.de
            \______________ ____________ http://toerring.de

            Comment

            • Yanb

              #7
              Re: how to specify power of number

              Antoninus Twink <nospam@nospam. invalidwrote in
              news:slrng0h483 .166.nospam@nos pam.invalid:
              On 18 Apr 2008 at 11:01, Bartc wrote:
              >You would have to use pow(256,3) which uses floating point arithmetic
              >-- not recommended, even though the compiler is likely to optimise.
              >>
              >Your code is fine as it is, the compiler will optimise 256*256*256 to
              >*16777216 or <<24. Or just write those in yourself.
              >
              For general integer powers, a simple square-and-multiply algorithm is
              a good bet, e.g.
              >
              unsigned long long power(unsigned a, unsigned b)
              {
              unsigned long long r, bit, pow;
              for(bit=r=1, pow=a; bit<=b; bit<<=1, pow *= pow)
              if(b & bit)
              r*=pow;
              return r;
              }
              >
              The hardest part is checking for overflow - left as an exercise for
              the reader...
              >
              Thank you both. I must admit, that the code Is almost a mystery for me :-)

              Comment

              • Yanb

                #8
                Re: how to specify power of number

                jt@toerring.de (Jens Thoms Toerring) wrote in news:66rlpcF2lt sj2U1@mid.uni-berlin.de:

                [snip]

                Thank you for a good advices, Jens. Good to know it.

                Comment

                • Noob

                  #9
                  Re: how to specify power of number

                  Yanb wrote:
                  I made a C function, which takes IP adress from string and converts
                  to unsigned long int.
                  Your function sounds like inet_aton().

                  (comp.unix.prog rammer is a better place to discuss such a function.)


                  Comment

                  • Antoninus Twink

                    #10
                    Re: how to specify power of number

                    On 18 Apr 2008 at 14:05, Yanb wrote:
                    Antoninus Twink <nospam@nospam. invalidwrote:
                    >For general integer powers, a simple square-and-multiply algorithm is
                    >a good bet, e.g.
                    >>
                    >unsigned long long power(unsigned a, unsigned b)
                    >{
                    > unsigned long long r, bit, pow;
                    > for(bit=r=1, pow=a; bit<=b; bit<<=1, pow *= pow)
                    > if(b & bit)
                    > r*=pow;
                    > return r;
                    >}
                    >>
                    >The hardest part is checking for overflow - left as an exercise for
                    >the reader...
                    >>
                    >
                    Thank you both. I must admit, that the code Is almost a mystery for me :-)
                    Well, it's overkill for exponents small enough not to overflow a
                    unit64_t, but the idea is this: naively, to raise a to the power b takes
                    b integer multiplies (a*a*...*a, b times). But actually, you can do this
                    using more like log(b) multiplies by repeatedly squaring to compute a^2,
                    a^4, a^8, ... and then multiplying those terms corresponding to
                    exponents of 2 that occur in the binary expansion of b. For example, if
                    b=7, then a^7 = a^(1+2+4) = a * a^2 * a^4.

                    Comment

                    • user923005

                      #11
                      Re: how to specify power of number

                      On Apr 18, 2:23 pm, Antoninus Twink <nos...@nospam. invalidwrote:
                      On 18 Apr 2008 at 14:05, Yanb wrote:
                      >
                      >
                      >
                      >
                      >
                      Antoninus Twink <nos...@nospam. invalidwrote:
                      For general integer powers, a simple square-and-multiply algorithm is
                      a good bet, e.g.
                      >
                      unsigned long long power(unsigned a, unsigned b)
                      {
                        unsigned long long r, bit, pow;
                        for(bit=r=1, pow=a; bit<=b; bit<<=1, pow *= pow)
                          if(b & bit)
                            r*=pow;
                        return r;
                      }
                      >
                      The hardest part is checking for overflow - left as an exercise for
                      the reader...
                      >
                      Thank you both. I must admit, that the code Is almost a mystery for me :-)
                      >
                      Well, it's overkill for exponents small enough not to overflow a
                      unit64_t, but the idea is this: naively, to raise a to the power b takes
                      b integer multiplies (a*a*...*a, b times). But actually, you can do this
                      using more like log(b) multiplies by repeatedly squaring to compute a^2,
                      a^4, a^8, ...  and then multiplying those terms corresponding to
                      exponents of 2 that occur in the binary expansion of b. For example, if
                      b=7, then a^7 = a^(1+2+4) = a * a^2 * a^4.
                      If we look at his original post (and knowing he is just turning these
                      TCP/IP addresses into 4 byte integers):
                      "
                      numericip=atoi( textip[0])*256*256*256+a toi(textip[1])*256*256+atoi( textip[2­])*256+atoi(text ip[3]);"

                      It could clearly be done as {assuming textip[] is an array of unsigned
                      char} as:
                      numericip = (unsigned long)textip[0] << 24 +
                      (unsigned long)textip[1] << 16 +
                      (unsigned long)textip[2] << 8 +
                      (unsigned long)textip[3] ;

                      Or {better yet} simply use inet_aton() {which is also fine for
                      Winsock, though WSAStringToAddr ess() is an alternative}. That is what
                      would be normally done to retrieve a TCP/IP address from a dotted
                      address string.

                      HOWEVER!

                      The OP should keep in mind that inet_aton() does NOT support IPv6 and
                      that getnameinfo() should be used instead for IPv4/v6 dual stack
                      support.

                      IMO-YMMV.

                      To the O.P.:
                      You can't go wrong with "Unix Network Programming" By W. Richard
                      Stevens (the same ideas work everywhere so don't be concerned if you
                      are doing Windows TCP/IP.

                      I don't know of any good reference works for IPv6 (I just use RFCs for
                      that).

                      Comment

                      • Antoninus Twink

                        #12
                        Re: how to specify power of number

                        On 18 Apr 2008 at 21:46, user923005 wrote:
                        If we look at his original post (and knowing he is just turning these
                        TCP/IP addresses into 4 byte integers):
                        "
                        numericip=atoi( textip[0])*256*256*256+a toi(textip[1])*256*256+atoi( textip[2­])*256+atoi(text ip[3]);"
                        >
                        It could clearly be done as {assuming textip[] is an array of unsigned
                        char} as:
                        numericip = (unsigned long)textip[0] << 24 +
                        (unsigned long)textip[1] << 16 +
                        (unsigned long)textip[2] << 8 +
                        (unsigned long)textip[3] ;
                        True, and someone had already suggested this. But the discussion
                        broadened, and someone claimed that using pow() was the best way to
                        raise integers to (positive) integer powers: it was this assertion that
                        I was responding to.
                        Or {better yet} simply use inet_aton() {which is also fine for
                        Winsock, though WSAStringToAddr ess() is an alternative}. That is what
                        would be normally done to retrieve a TCP/IP address from a dotted
                        address string.
                        >
                        HOWEVER!
                        >
                        The OP should keep in mind that inet_aton() does NOT support IPv6 and
                        that getnameinfo() should be used instead for IPv4/v6 dual stack
                        support.
                        Good advice.
                        To the O.P.:
                        You can't go wrong with "Unix Network Programming" By W. Richard
                        Stevens
                        Agreed.

                        Comment

                        • Dann Corbit

                          #13
                          Re: how to specify power of number

                          "Antoninus Twink" <nospam@nospam. invalidwrote in message
                          news:slrng0i6b9 .7i7.nospam@nos pam.invalid...
                          On 18 Apr 2008 at 21:46, user923005 wrote:
                          >If we look at his original post (and knowing he is just turning these
                          >TCP/IP addresses into 4 byte integers):
                          >"
                          >numericip=atoi (textip[0])*256*256*256+a toi(textip[1])*256*256+atoi( textip[2­])*256+atoi(text ip[3]);"
                          >>
                          >It could clearly be done as {assuming textip[] is an array of unsigned
                          >char} as:
                          >numericip = (unsigned long)textip[0] << 24 +
                          > (unsigned long)textip[1] << 16 +
                          > (unsigned long)textip[2] << 8 +
                          > (unsigned long)textip[3] ;
                          >
                          True, and someone had already suggested this. But the discussion
                          broadened, and someone claimed that using pow() was the best way to
                          raise integers to (positive) integer powers: it was this assertion that
                          I was responding to.
                          Because math coprocessors are awfully fast now, I guess that pow(2.0,k) is
                          nearly as fast as bit shifts and additions, but there is a bigger problem
                          with using pow(2,x) to find exact powers of 2. It should not be unexpected
                          for pow(2.0,24) to return 16777215.999999 999 and if you assign that to an
                          integer, it probably won't be what is wanted unless you are clever enough to
                          round it -- ceil() won't help either because we might also have seen
                          16777215.000000 1 or something like that. The Cephes collection of math
                          functions {for instance} uses a ratio of a cubic polynomial divided by a
                          quartic polynomial to form the approximation.

                          Likely, many implementations will actually recognize integral inputs (my C++
                          compiler definitely does this -- even sometimes complaining about ambiguity
                          over argument type) but there is no reason to expect that to happen.

                          So I guess I am really agreeing with you. If you want small and exact
                          powers of 2, then bit shifting of unsigned integers is the most sensible
                          method. It will be fast (probably faster than pow()) and also exact. The
                          meaning of either construct is clear to any C programmer and so the argument
                          of writing the code that is most clear does not come into play here.
                          >Or {better yet} simply use inet_aton() {which is also fine for
                          >Winsock, though WSAStringToAddr ess() is an alternative}. That is what
                          >would be normally done to retrieve a TCP/IP address from a dotted
                          >address string.
                          >>
                          >HOWEVER!
                          >>
                          >The OP should keep in mind that inet_aton() does NOT support IPv6 and
                          >that getnameinfo() should be used instead for IPv4/v6 dual stack
                          >support.
                          >
                          Good advice.
                          >
                          >To the O.P.:
                          >You can't go wrong with "Unix Network Programming" By W. Richard
                          >Stevens
                          >
                          Agreed.
                          Well look here, it appears that we agree on everything. At least in this
                          post.
                          ;-)


                          ** Posted from http://www.teranews.com **

                          Comment

                          • Dann Corbit

                            #14
                            Re: how to specify power of number

                            "Dann Corbit" <dcorbit@connx. comwrote in message
                            news:14653$4809 20eb$8464@news. teranews.com...
                            [snip]
                            Because math coprocessors are awfully fast now, I guess that pow(2.0,k) is
                            nearly as fast as bit shifts and additions, but there is a bigger problem
                            with using pow(2,x) to find exact powers of 2. It should not be
                            unexpected for pow(2.0,24) to return 16777215.999999 999 and if you assign
                            that to an integer, it probably won't be what is wanted unless you are
                            clever enough to round it -- ceil() won't help either because we might
                            also have seen 16777215.000000 1 or something like that. The Cephes
                            collection of math
                            Of course I meant 16777216.000000 1 -- I would be pretty upset with a double
                            math library that can't even give me back 8 significant digits of precision.
                            functions {for instance} uses a ratio of a cubic polynomial divided by a
                            quartic polynomial to form the approximation.
                            [snip]


                            ** Posted from http://www.teranews.com **

                            Comment

                            • Tim Prince

                              #15
                              Re: how to specify power of number

                              Because math coprocessors are awfully fast now, I guess that pow(2.0,k) is
                              nearly as fast as bit shifts and additions, but there is a bigger problem
                              with using pow(2,x) to find exact powers of 2. It should not be unexpected
                              for pow(2.0,24) to return 16777215.999999 999 and if you assign that to an
                              integer, it probably won't be what is wanted unless you are clever enough to
                              round it -- ceil() won't help either because we might also have seen
                              16777215.000000 1 or something like that. The Cephes collection of math
                              functions {for instance} uses a ratio of a cubic polynomial divided by a
                              quartic polynomial to form the approximation.
                              >
                              Likely, many implementations will actually recognize integral inputs (my C++
                              compiler definitely does this -- even sometimes complaining about ambiguity
                              over argument type) but there is no reason to expect that to happen.
                              >
                              It's almost obligatory for an implementation of pow() to special case
                              integral exponents, so as to handle negative operands, as well as provide
                              accuracy. I thought Cephes did this.
                              In case this doesn't happen, it doesn't seem too far fetched to specify
                              functions such as lrint(), supplying your own code if your position is
                              that C99 isn't portable enough.

                              Comment

                              Working...