2

For example what would be the process of converting the integer 1023 into ascii characters of

0x31 (1) 0x30 (0) 0x32 (2) 0x33 (3)

Not looking for any library functions (I know of Serial.print() and what not). I am trying to serially communicate an integer to the serial monitor, and I'd like to know what the process would be for an algorithm to take an integer and make each digit its corresponding ascii character

3
  • Is this what you are trying to do? cplusplus.com/reference/cstdlib/itoa
    – VE7JRO
    Commented Nov 15, 2019 at 21:39
  • If you search "c++ implementation itoa" you can find examples for this
    – chrisl
    Commented Nov 15, 2019 at 21:44
  • how about float value? can float value convert using itoa()?
    – Norazlan K
    Commented Oct 20, 2020 at 12:48

1 Answer 1

4

To convert a whole number to a char array in one go use the itoa function. That sounds like what you actually need.

To convert one digit from decimal to ascii just add '0', the ascii value for a 0. If you just want to try to understand what's going on, it's something like this.

char result[4] = {0};
int num = 345;

int digit = num % 10;  // get the 5 off the end
result[2] = digit + '0';  // convert to ascii and store
num /= 10;   // get rid of the 5
digit = num % 10;   // get the 4 off the end
result[1] = digit + '0';  // convert to ascii and store
num /= 10;   // get rid of the 4
digit = num % 10;   // get the 3 off the end
result[0] = digit + '0';  // convert to ascii and store

Serial.print(result);  // prints "345"
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.