Re: how to specify power of number
- From: user923005 <dcorbit@xxxxxxxxx>
- Date: Fri, 18 Apr 2008 14:46:59 -0700 (PDT)
On Apr 18, 2:23 pm, Antoninus Twink <nos...@xxxxxxxxxxxxxx> wrote:
On 18 Apr 2008 at 14:05, Yanb wrote:
Antoninus Twink <nos...@xxxxxxxxxxxxxx> wrote:
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+atoi(textip[1])*256*256+atoi(textip[2])*256+atoi(textip[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 WSAStringToAddress() 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).
.
- Follow-Ups:
- Re: how to specify power of number
- From: Nick Keighley
- Re: how to specify power of number
- From: Antoninus Twink
- Re: how to specify power of number
- References:
- how to specify power of number
- From: Yanb
- Re: how to specify power of number
- From: Bartc
- Re: how to specify power of number
- From: Antoninus Twink
- Re: how to specify power of number
- From: Yanb
- Re: how to specify power of number
- From: Antoninus Twink
- how to specify power of number
- Prev by Date: Re: how to specify power of number
- Next by Date: Re: how to specify power of number
- Previous by thread: Re: how to specify power of number
- Next by thread: Re: how to specify power of number
- Index(es):