1

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

2

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

Here is a test sketch using iota().

int number = 1023;
const byte numberLength = 4;
char outputBuffer[numberLength + 1];

void setup(){

  Serial.begin(9600);

  itoa(number, outputBuffer, 10);

  for(byte i = 0; i < numberLength; i++){
    Serial.println(outputBuffer[i]);
  }
  Serial.println();

  for(byte i = 0; i < numberLength; i++){
    Serial.print("0x");
    Serial.println(outputBuffer[i], HEX);
  }

}

void loop(){}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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