I’m trying to get every odd number in my barcode. For example my barcode is 100101000316 and im trying to get 1 0 0 0 0 1. How can i get the specific digit in my barcode? This is my code
private string checkDigit(string barcode)
{
int OddNum = 0;
int OddNumSum;
for (var num = 0; barcode.Length > num; num += 2 )
{
OddNum = OddNum + barcode[num];
}
}
but the value im getting in my breakpoint in visual studio is 49’1′, 48, ‘0’, 47 ‘0’, 46 ‘0’, 45 ‘0’, 44 ‘1’ and the value that im getting is the 49, 48 …
What i need is inside the single quote.
>Solution :
The [] operator of a string returns a char. You’re getting the numeric (ASCII) value of that digit. Since the digits are consecutive ASCII characters, the easiest thing to do is subtract the charater '0', and thus get the offset from it, which would be the digit you’re looking for.
Then, it’s just a matter of summing them up:
private static int checkDigit(string barcode)
{
int OddNumSum = 0;
for (var num = 0; barcode.Length > num; num += 2 )
{
OddNumSum += barcode[num] - '0';
}
return OddNumSum;
}