Jump to content
Sign in to follow this  
Greg

Too complicated!

Recommended Posts

Hi,

I would like to do this:

if((shortA+shortB)>0xFFFF) {
shortA++;
}

but the compiler tells me it is too complicated as they are 16 bit variables, could anyone help me by giving me an example of how i could do it differently?

Thanks

Greg

Share this post


Link to post
Share on other sites

It would be helpful to see the context of this code;

what you are really trying to accomplish.

 

... The value of a 16 bit integer can never be

   greater than 0xffff ...

 

Jim

Share this post


Link to post
Share on other sites
Guest Greg

Hi,

What i am actually trying to do is add two 16 bit variables:

 

shortA=shortA+shortB;

 

There is a high chance of this over flowing, and i want to detect whether there will be an overflow or not when i add them together. if i just do that sum and their is an overflow the carry bit in the status register doesnt seem to get set so i am not sure how to do detect it.

Thanks,

Greg

Share this post


Link to post
Share on other sites

Here is one approach that popped into my head.

I have tested a few values with it, but can't guarentee

that it will work in all cases...

 

The only time that the sum will be less than either (both?)

of the source operands will be if there is an overflow.

 

So, here is one way you might code it:

 

short temp_sum;

 

temp_sum = shortA + shortB;

 

if ( (temp_sum < shortA) || (temp_sum < shortB) )

{

  shortA++;

}

 

See what happens... ;-)

 

Jim

Share this post


Link to post
Share on other sites
Guest Greg

Hi,

Thanks for all the replies i really appreciate all the assistance!

The answer JJHawg gives is spot on! and works perfectly!

Thank you!

Greg

Share this post


Link to post
Share on other sites

Join the conversation

You are posting as a guest. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...