473,800 Members | 2,475 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Quickest way for even numbers

Hi all!
I want to check whether a number is odd or even. I've made an algorithm
but I believe there should be a faster one ( maybe a macro ).
Here it goes :

int iseven ( int number )
{
int first;
int tempnum;

tempnum = number;

first = number >> 1;
number = first << 1;

if ( tempnum == number )
return 0;

return 1;
}
Thanks in advance
Nov 14 '05
15 4293
"Mark A. Odell" <od*******@hotm ail.com> wrote in message news:<Xn******* *************** **********@130. 133.1.4>...
Da*****@cern.ch (Dan Pop) wrote in news:cd******** **@sunnews.cern .ch: <snip>
with Diab 5.0.3. I guess Diab's not as smart as it could be. The var.
'number' is in r3 of course.


<OT>
Given the absolutely shameful code I've seen in parts of certain
WindRiver products, I'm not too surprised. This is Compilers-101
stuff. Ugh.
</OT>
Mark F. Haigh
mf*****@sbcglob al.net
Nov 14 '05 #11
In <84************ **************@ posting.google. com> ol*****@inspire .net.nz (Old Wolf) writes:
Emmanuel Delahaye <em***@YOURBRAn oos.fr> wrote:
Emmanuel Delahaye avait prétendu :
> inline int is_even (long long number)
> {
> return (number & 0x1ull) == 0:
return ((unsigned long long) number & 0x1ull) == 0:
> }


Why would you do that? Since one operand of the '&' is unsigned
long long, the other will be promoted to it without a cast.

More readable, would be:

return (number & 1) == 0;


More readable, but less portable, as long as number has a signed type,
as is actually the case in the code under discussion.

I agree that Emmanuel is baroque, as usual, and his idea only requires

return (number & 1ULL) == 0;

because 1ULL is enough to force the conversion of number to unsigned
long long. But you're simplifying too much.
or !(number & 1) if you prefer, as then the 1 (1 decimal = 1 hex)
will be promoted to match 'number'. I would even go for
'int' instead of 'long long' since I don't care about any
bits other than the least-significant one.


Ever heard of one's complement? According to your version, -1 is an
even number on implementations using this representation. For maximal
portability, any micro-optimisation based on examining the LS bit must
ensure that the number is converted to an unsigned integer type.
And the cheapest way of doing that is by choosing the right type for
the mask.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #12
Da*****@cern.ch (Dan Pop) wrote:
ol*****@inspire .net.nz (Old Wolf) writes:
Emmanuel Delahaye <em***@YOURBRAn oos.fr> wrote:
inline int is_even (long long number)
{
return (number & 0x1ull) == 0:
return ((unsigned long long) number & 0x1ull) == 0:
}


More readable, would be:

return (number & 1) == 0;


More readable, but less portable, as long as number has a signed type,
as is actually the case in the code under discussion.


I saw that he was casting to unsigned, which seemed indicate a lack of
interest in negative values. (But in fact doesn't, as you pointed out).
Ever heard of one's complement? According to your version, -1 is an
even number on implementations using this representation.


I wasn't sure. I've often heard "C works on values, not representations "
mentioned here, ie. (x & 1) should be the same regardless of
representation. I haven't ever had access to anything other than 2's c.,
so was unable to test it out.
Nov 14 '05 #13
Old Wolf wrote:

Da*****@cern.ch (Dan Pop) wrote:
ol*****@inspire .net.nz (Old Wolf) writes:
Emmanuel Delahaye <em***@YOURBRAn oos.fr> wrote:

> inline int is_even (long long number)
> {
> return (number & 0x1ull) == 0:

return ((unsigned long long) number & 0x1ull) == 0:

> }

More readable, would be:

return (number & 1) == 0;


More readable, but less portable, as long as number has a signed type,
as is actually the case in the code under discussion.


I saw that he was casting to unsigned, which seemed indicate a lack of
interest in negative values. (But in fact doesn't, as you pointed out).
Ever heard of one's complement? According to your version, -1 is an
even number on implementations using this representation.


I wasn't sure. I've often heard "C works on values,
not representations " mentioned here,
ie. (x & 1) should be the same regardless of
representation.


C works on values,
but sometimes representation counts for something,
especially with bitwise operators.

If you have
signed char integer = -1;
then
((unsigned char)integer)
would equal UCHAR_MAX on any implementation,
but
(*(unsigned char *)&integer)
would be equal to:
(UCHAR_MAX) on two's complement
(UCHAR_MAX - 1) on one's complement
(UCHAR_MAX / 2 + 2) on signed magnitude

--
pete
Nov 14 '05 #14
In <84************ **************@ posting.google. com> ol*****@inspire .net.nz (Old Wolf) writes:
Da*****@cern.c h (Dan Pop) wrote:
ol*****@inspire .net.nz (Old Wolf) writes:
>Emmanuel Delahaye <em***@YOURBRAn oos.fr> wrote:
>
> > inline int is_even (long long number)
> > {
> > return (number & 0x1ull) == 0:
>
> return ((unsigned long long) number & 0x1ull) == 0:
>
> > }
>
>More readable, would be:
>
> return (number & 1) == 0;
More readable, but less portable, as long as number has a signed type,
as is actually the case in the code under discussion.


I saw that he was casting to unsigned, which seemed indicate a lack of
interest in negative values. (But in fact doesn't, as you pointed out).
Ever heard of one's complement? According to your version, -1 is an
even number on implementations using this representation.


I wasn't sure. I've often heard "C works on values, not representations "
mentioned here, ie. (x & 1) should be the same regardless of
representation .


4 Some operators (the unary operator ~, and the binary operators
<<, >>, &, ^, and |, collectively described as bitwise
operators) are required to have operands that have integer
type. These operators return values that depend on the internal
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^
representations of integers, and have implementation-defined
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^
and undefined aspects for signed types.
I haven't ever had access to anything other than 2's c.,
so was unable to test it out.


Neither had I, but I have a brain and can use it.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #15
[given a "test for even" program that just does "(number % 2) == 0"]
Da*****@cern.c h (Dan Pop) wrote in news:cd******** **@sunnews.cern .ch:
The code generated from my version by gcc on x86, for a long int
parameter, is:

xorl %eax, %eax
testb $1, 4(%esp)
sete %al
ret

In article <Xn************ *************** *****@130.133.1 .4>
Mark A. Odell <od*******@hotm ail.com> writes:Pretty tight, with return (number % 2) == 0 I get

srawi r0,r3,1
addze r0,r0
mulli r0,r0,2
subf r12,r0,r3
cntlzw r3,r12
rlwinm r3,r3,27,5,31
blr

and with return (number & 1U) == 0;
rlwinm r12,r3,0,31,31
cntlzw r3,r12
rlwinm r3,r3,27,5,31
blr

with Diab 5.0.3. I guess Diab's not as smart as it could be.


I am not sure why we seem to consider Diab so wonderful myself. :-)
Here is what I get using GCC ("ccpcc ... -O2 ...") for a tiny
"return (number % 2) == 0" function:

andi. 0,3,1
stwu 1,-16(1)
addi 1,1,16
mfcr 3
rlwinm 3,3,3,1
blr

I do not see the point of the manipulation of r1 here, but you can
see that the "mod 2" has been changed to "mask with constant 1"
(assuming you realize that "andi" takes two register numbers and
a constant, so that 0,3,1 means "put result in r0, mask r3 with
literal constant 1" -- ppc assembly gives me a headache :-) -- and
in this case we really only want the condition codes for the later
mfcr).

If you use "(n & 1) == 0" you get an "xor" instead of an "and"
(with gcc), turning the code into "return (n ^ 1) & 1" in effect.
(The pointless stack manipulations -- stwu and addi -- persist.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #16

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

Similar topics

6
4137
by: me | last post by:
Hi guys - the question is in the subject line. I thought of one quick way: std::ifstream input("myfile.dat") ; std::istreambuf_iterator beg(input), end ; std::vector DataFile(beg,end) ;
4
1677
by: puzzlecracker | last post by:
I am using cpp by the way? Thanks
6
1552
by: Deano | last post by:
I think my brain has short-circuited again :) Is this the quickest way to check for the existence of a given value in an array? e.g For i = 0 To rrst.RecordCount If myArray(i) = DLookup("ID", "tblmain", "Salary = " & varSomeValue) Then
0
1021
by: N k via DotNetMonster.com | last post by:
What is the quickest way to find the index of the first letter in a richTextBox? -- Message posted via http://www.dotnetmonster.com
6
8961
by: Jozef Jarosciak | last post by:
Quickest way to find the string in 1 dimensional string array! I have a queue 1 dimensional array of strings called 'queue' and I need a fast way to search it. Once there is match, I don't need to search any longer. Currently I am using this code. But I think it's too slow, because it runs through whole dimension. I know this is trivial question, but is there any way to stop this loop, or better way to search? I mean - FASTER?
2
1413
by: Emmanuel | last post by:
Hi there, My client would like to process an xml file. the structure of which is as below. <xml> <stockitem> <releaseddate>.....date value...</releaseddate> <...aditional tags for additional info> </stockitem> <stockitem>
17
4632
by: Ron | last post by:
I want to write a program that will accept a number in a textbox for example 23578 and then in a label will display the sum of the odd and even number like this... the textbox containsthe number 23578 the label would say: Sumof odd number is: 15 Sum of even number is: 10 any ideas?
30
29698
by: bdsatish | last post by:
The built-in function round( ) will always "round up", that is 1.5 is rounded to 2.0 and 2.5 is rounded to 3.0. If I want to round to the nearest even, that is my_round(1.5) = 2 # As expected my_round(2.5) = 2 # Not 3, which is an odd num I'm interested in rounding numbers of the form "x.5" depending upon whether x is odd or even. Any idea about how to implement it ?
18
4916
by: =?ISO-8859-1?Q?Ney_Andr=E9_de_Mello_Zunino?= | last post by:
Hello. It seems a year is all it takes for one's proficiency in C++ to become too rusty. Professionally, I've been away from the language (and from programming in general), but I still preserve an appreciation for it. So I decided to toy with some idea, just for fun and for evaluating how rusty I'd become. "Let me write a simple functor for sorting the elements of a collection! I will start with a simple collection of integers.", I...
0
9691
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10276
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10035
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7580
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6813
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2945
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.