# ASCII to decimal conversion of a two digit number

Hey everyone, My input to the serial terminal would be a two digit number, like 45. I want to read this number and extract integers 4 and 5 separately in two variables in my code. 45 will be received as d = 5253, further I used mod and '/' operation to get x= 52 and x=53 separately and then subtract each by 48 that would give me 4 and 5 separately. But that's not happening. d % 100 is giving me 5253 itlesf i.e, (52-48)(53-48) and the subtraction by 48 will give me 45. Mod operation can not be used! Could u suggest me a better option?

The serial terminal should be returning 2 ascii characters for ‘4’ and ‘5’, from which you subtract the ascii for ‘0’ to get the number.

abhiramks10: Hey everyone, My input to the serial terminal would be a two digit number, like 45. I want to read this number and extract integers 4 and 5 separately in two variables in my code. 45 will be received as d = 5253, further I used mod and '/' operation to get x= 52 and x=53 separately and then subtract each by 48 that would give me 4 and 5 separately. But that's not happening. d % 100 is giving me 5253 itlesf i.e, (52-48)(53-48) and the subtraction by 48 will give me 45. Mod operation can not be used! Could u suggest me a better option?

If you have a single 16 bit variable which contains decimal 5253 (ASCII "45"), you can extract the values this way:

``````    int d = 5253; // your original data
char first = (d >> 8); // slide the "52" down by 8 bits (the top 8 bits are zero-filled)
char second = (d & 0xFF); // mask off the top 8 bits, copy what's left (the bottom) to "second"

// at this point, "first" is 52 decimal and "second" is 53 decimal
// now convert them to numbers (remove the ASCII "bias")

first -= '0'; // subtract ascii zero (decimal 48) from "first"
second -= '0'; // same thing with the "second" value

// at this point, "first" is decimal 4 and "second" is decimal 5.
``````

Now, I don't know what you're doing with this stuff, but if you're sending commands to something via the serial terminal, this a really klunky way to do it. A simple "readline" function and then "atoi()" to get the received value is a LOT easier, simpler, faster and more flexible (you are not locked into 2 digit "packets").

If this is what you are trying to do and you want the readline and associated code, let me know.

Hope this helps.

Look at the Arduino code in this demo.

If you want the digits 4 and 5 to be treated as two separate numbers why not put a comma between them 4,5

...R