Board index » cppbuilder » Problems with Long Integers

Problems with Long Integers


2008-02-05 12:55:32 AM
cppbuilder102
I have two word values I have to do a little bit of simple math on the end
up with an unsigned long. But no matter what I try, it keeps rolling over
like its an unsigned int.
wVal[0] contains 82
wVal[1] contains 563
ulHours "should" contain 82563 but does not, it always returns 17027.
unsigned long ulHours;
//verify my variables
printf("Thousands of Hours %u \r\n", wVal[0]); //Displays 82
printf("Hundreds of Hours %u \r\n", wVal[1]); //Displays 563
ulHours = ((wVal[0] * 1000) + wVal[1]);
printf("HOURS ********* %lu \r\n",ulHours); //Displays 17027
I tried this for grins...
ulHours = (unsigned long)((wVal[0] * 1000) + wVal[1]);
printf("HOURS ********* %lu \r\n",(unsigned long)ulHours); //Displays
17027
Why am I rolling over?
 
 

Re:Problems with Long Integers

Richard wrote:
Quote
ulHours = ((wVal[0] * 1000) + wVal[1]);
ulHours = (unsigned long)((wVal[0] * 1000) + wVal[1]);

Why am I rolling over?
Because you are still working with words when you do your arithmetic.
Try converting everything to long first:
ulHours = ((unsigned long)wVal[0] * 1000ul) + (unsigned long)wVal[1];
 

Re:Problems with Long Integers

Earlier, when I tried this, it also worked???
ulHours = ((wVal[0] * 1000ul) + wVal[1]);
I'm too used to Delphi and this keeps biting me in defferent ways.
"Bob Gonder" < XXXX@XXXXX.COM >wrote in message
Quote
Richard wrote:

>ulHours = ((wVal[0] * 1000) + wVal[1]);
>ulHours = (unsigned long)((wVal[0] * 1000) + wVal[1]);
>
>Why am I rolling over?

Because you are still working with words when you do your arithmetic.
Try converting everything to long first:
ulHours = ((unsigned long)wVal[0] * 1000ul) + (unsigned long)wVal[1];


 

{smallsort}

Re:Problems with Long Integers

Richard wrote:
Quote
>>ulHours = ((wVal[0] * 1000) + wVal[1]);
Word * 1000 is still a word.
Word + word is still word.
Unsigned long = word is value of word.
Quote
ulHours = ((wVal[0] * 1000ul) + wVal[1]);
Word * unsigned long is an unsigned long.
Unsigned long + word is unsigned long.
Unsigned long = unsigned long is value of unsigned long.
Quote
Earlier, when I tried this, it also worked???
Trick is to promote the operand size before overflow happens.