473,407 Members | 2,312 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

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+atoi(textip[1])*256*256+atoi(textip[2])*256+atoi(textip[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.
Jun 27 '08 #1
22 1669
Yanb <Ya**@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+atoi(textip[1])*256*256+atoi(textip[2])*256+atoi(textip[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.
Jun 27 '08 #2

"Yanb" <Ya**@whatever.invalidwrote in message
news:fu**********@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+atoi(textip[1])*256*256+atoi(textip[2])*256+atoi(textip[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
Jun 27 '08 #3
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...

Jun 27 '08 #4
Ben Bacarisse <be********@bsb.me.ukwrote in
news:87************@bsb.me.uk:
Yanb <Ya**@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+atoi(textip[1])*256*256+atoi(tex
tip[2])*256+atoi(textip[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?
Jun 27 '08 #5

Yanb <Ya**@whatever.invalidwrote:
Ben Bacarisse <be********@bsb.me.ukwrote in
news:87************@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
Jun 27 '08 #6
Antoninus Twink <no****@nospam.invalidwrote in
news:sl*******************@nospam.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 :-)
Jun 27 '08 #7
jt@toerring.de (Jens Thoms Toerring) wrote in news:66*************@mid.uni-berlin.de:

[snip]

Thank you for a good advices, Jens. Good to know it.
Jun 27 '08 #8
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.programmer is a better place to discuss such a function.)

http://www.kernel.org/doc/man-pages/...et_addr.3.html
Jun 27 '08 #9
On 18 Apr 2008 at 14:05, Yanb wrote:
Antoninus Twink <no****@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.

Jun 27 '08 #10
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+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).
Jun 27 '08 #11
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+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] ;
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 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.
Good advice.
To the O.P.:
You can't go wrong with "Unix Network Programming" By W. Richard
Stevens
Agreed.

Jun 27 '08 #12
"Antoninus Twink" <no****@nospam.invalidwrote in message
news:sl*******************@nospam.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+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] ;

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.999999999 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.0000001 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 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.

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 **
Jun 27 '08 #13
"Dann Corbit" <dc*****@connx.comwrote in message
news:14*****************@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.999999999 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.0000001 or something like that. The Cephes
collection of math
Of course I meant 16777216.0000001 -- 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 **
Jun 27 '08 #14
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.999999999 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.0000001 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.
Jun 27 '08 #15
On Apr 18, 6:21*pm, Tim Prince <tpri...@nospamcomputer.orgwrote:
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.999999999 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.0000001 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 (myC++
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.
I looked, it does.
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.
Of course if you just need a small power of 2, a shift will do
nicely. Even though most implementations will probably notice integer
values for both base and exponent, there is no requirement for them to
do that and not even a requirement to produce an answer within 1/2 ULP
of what is correct {though some compilers will try hard to do it}.
Jun 27 '08 #16
On Apr 18, 10:46*pm, user923005 <dcor...@connx.comwrote:
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] ;
congratulations you have just hit C pitfall number 57.

<spoiler>





just what is the precedence of +? and of <<?

write out 10,000,000 times.
"I must not mix logical and arithmetic operators"

And it was nice to see my compiler (Microsoft) issued a warning
for the code.
--
Nick Keighley
Jun 27 '08 #17
Nick Keighley wrote:
On Apr 18, 10:46 pm, user923005 <dcor...@connx.comwrote:
>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] ;
just what is the precedence of +? and of <<?
Given that << and >are on a par with multiply and divide, what was the
reason for the silly choice of precendence?

--
Bart
Jun 27 '08 #18
[ Cross-posting to comp.unix.programmer and setting Followup-To ]

user923005 wrote:
The OP should keep in mind that inet_aton() does NOT support IPv6
OK.
and that getnameinfo() should be used instead for IPv4/v6 dual
stack support.
inet_pton() seems more appropriate.

http://www.kernel.org/doc/man-pages/...et_pton.3.html

<quote>
This function converts the character string src into a network address
structure in the af address family, then copies the network address
structure to dst.
</quote>
Jun 27 '08 #19
On Apr 19, 7:05*am, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
On Apr 18, 10:46*pm, user923005 <dcor...@connx.comwrote:
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] ;

congratulations you have just hit C pitfall number 57.

<spoiler>

just what is the precedence of +? and of <<?

write out 10,000,000 times.
"I must not mix logical and arithmetic operators"

And it was nice to see my compiler (Microsoft) issued a warning
for the code.
Should have been:
numericip = (unsigned long)textip[0] << 24 |
(unsigned long)textip[1] << 16 |
(unsigned long)textip[2] << 8 |
(unsigned long)textip[3] ;

which is how I would normally code it, but I thought the other
expression would be more clear. That's what I get for not checking.

Jun 27 '08 #20
Bartc wrote:
Given that << and >are on a par with multiply and divide,
what was the reason for the silly choice of precendence?
Sometimes the gods fail to live up to mortal standards.

http://cm.bell-labs.com/cm/cs/who/dmr/chist.html

--
Peter
Jun 27 '08 #21
Peter Nilsson wrote:
Bartc wrote:
>Given that << and >are on a par with multiply and divide,
what was the reason for the silly choice of precendence?

Sometimes the gods fail to live up to mortal standards.

http://cm.bell-labs.com/cm/cs/who/dmr/chist.html
The reference explains the peculiar precedence of &&,
but I see nothing about << and >there. Have I missed
something? (Again?)

--
Eric Sosman
es*****@ieee-dot-org.invalid
Jun 27 '08 #22
Eric Sosman <es*****@ieee-dot-org.invalidwrote:
>
The reference explains the peculiar precedence of &&,
but I see nothing about << and >there. Have I missed
something? (Again?)
I don't think so. But I believe the precedence of << and >is the same
as it was back in BCPL.

-Larry Jones

I've never seen a sled catch fire before. -- Hobbes
Jun 27 '08 #23

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
by: Zero | last post by:
Hi, I am calculating an integer to the pwer of a large integer, e.g. 2^5000. It turns out that the result I always get is zero. I am sure that the result is too large to store in such type...
17
by: Matt | last post by:
Give a one-line C expression to test whether a number is a power of 2. No loops allowed.
11
by: MJ | last post by:
Hi I have question about the C. I have a number X which is power of two X = 2 power n I need to find it using a Single C statement whether its a power of 2 or not I know that a number with...
16
by: JD | last post by:
Hi guys What's the best way to specify font size using CSS? I try to avoid absolute units like pt and px because then users can't resize the fonts in IE, but % and em are a complete pain to use...
6
by: Steve Kershaw | last post by:
This is stupid!!!! I have looked everywhere (in books, google, online....) to find out how to raise a number to a power and I can't find it!!! For example: given x = 10 y = x ^ 2; y would...
6
by: raghu | last post by:
is it possible to write a code using bitwise operators for checking whether a number is power of 2 or in general power of n (n=2,3,4,...)?? Thanks a lot. Regards, Raghu
10
by: David T. Ashley | last post by:
What is the most economical test in 'C' for "integer is a power of 2"? For example, something better than: void is_2_pow(int arg) { return((x == 1) || (x == 2) || (x == 4) || (x == 8) || (x...
6
by: maxthebaz | last post by:
Our machines have this requirement: if power failure occurs, many important variables are to be resumed from where they were interrupted after the machine is restarted (power on in this case). In...
12
by: calimero22 | last post by:
Hi I'musing the GMP Libraries Mathematics. I need to calculate 12345678987654321.1234567876554456 ^ 9876543212344556676.676767676 How can i do ? The two variables are type MPF. Thanks
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.