Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get specific digit in barcode as string

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading