c# - Why does 1 + 0 + 0 + 0 + 3 == 244? -


passing value of "01200000131" method:

private static int sumoddvals(string barcode) {     int cumulativeval = 0;     (int = 0; < barcode.length; i++)     {         if (i % 2 != 0)         {             messagebox.show(string.format("i {0}; barcode{0} {1}", i, barcode[i]));             cumulativeval += convert.toint16(barcode[i]);         }     }     messagebox.show(string.format("odd total {0}", cumulativeval));     return cumulativeval; } 

...returns "244"

i'm expecting return "4".

the first message box shows me i'd expect see, namely "1", "0" 3 times, "3", expect add "4", not "244".

you converting numerical char values int's here:

 cumulativeval += convert.toint16(barcode[i]); // indexer on string char 

what want.. convert string representation of number number.. not char value.. add tostring():

 cumulativeval += convert.toint16(barcode[i].tostring()); 

edit:

or, pointed out in comments:

 cumulativeval += convert.toint16(barcode[i] - '0'); 

result: 4.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

IIS->Tomcat Redirect: multiple worker with default -