On Feb 12, 3:13 pm, "Sylvester Hesp" <s.h...@oisyn.nl> wrote:
> "peter koch" <peter.koch.lar...@gmail.com> wrote in message
>
> news: oups.com...
>
>
>
>
>
> > On Feb 12, 2:35 pm, "Mr. Politics" <mrpolit...@gmail.com> wrote:
> >> On Feb 12, 8:18 am, "Sylvester Hesp" <s.h...@oisyn.nl> wrote:
>
> >> > "Mr. Politics" <mrpolit...@gmail.com> wrote in message
>
> >> >news: oups.com...
>
> >> > > On Feb 12, 8:05 am, "Mr. Politics" <mrpolit...@gmail.com> wrote:
> >> > >> This function keeps giving me negative values (esp. if I feed it
> >> > >> 64,153,160)
>
> >> > >> What gives?
>
> >> > > int quantity(char chrs[],int length)
> >> > > {
> >> > > int q = 0;
> >> > > int x;
> >> > > int c = 0;
>
> >> > > for (x=0; x<length;x++)
> >> > > {
> >> > > c = (int)chrs[x];
> >> > > q += c;
> >> > > }
> >> > > return q;
> >> > > }
>
> >> > char is probably signed on your platform (and with 8 bits, it can
> >> > possibly
> >> > only hold values between -128 and 127 inclusive)
>
> >> > - Sylvester
>
> >> For posterity, the fix... (Thank you!)
>
> >> int quantity(unsigned char chrs[],int length)
> >> {
> >> int q = 0;
> >> int x;
> >> int c = 0;
>
> >> for (x=0; x<length;x++)
> >> {
> >> c = (int)chrs[x];
> >> q += c;
>
> >> }
> >> return q;
>
> >> }
> > Instead of pulling hair out, you should pull your code in to a
> > debugger and see whats going on. One hint is that "casts are evil" is
> > almost always true.
>
> > /Peter
>
> While I agree with you, I don't really see how this particular situation
> changes when you just remove the cast to int
My hope was that the OP would realise that there would have to be a
"real" conversion, and not just a cast. I was seemingly to optimistic.
/Peter