Convert from integer to character string

I have been trying to write a function which can convert a number from an unsigned long integer to a readable ASCII character string. this is what I have come up with, but I am receiving some very strange characters in return.

could the problem be that I am telling a char to = an unsigned long int, (cString[i] = product[i])?

I am doing this for a school project.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void convertToString(unsigned long con) {  
  unsigned long product[10];
  char cString[10];
  const unsigned long begConvert = 10 ^ 10;
  unsigned long convert = begConvert;
  int i;
  int n;
  
  for(i = 0; i <= 9; i++) {               //Find numbers in decimal places from billion's place to 1's place (length of an unsigned long integer)
    product[i] = con/(10^(9-i));         //find the current decimal place
    for(n = 0; n < i; n++) {
      product[i] = product[i] - product[n] * 10 ^ i;    //subtract the numbers above the selected decimal place to get the exact number in the chosen decimal place.
    }
    cString[i] = product[i] + '0'; //convert number to a character value
  }
  Serial.println(cString);  //Send a character string of the number to the PC
}
Last edited on
Raisintoe wrote:
I have been trying to write a function which can convert a number from an unsigned long integer to a readable ASCII character string.
Your code doesn't look like this at all - can you clarify?
///////////////////////////////////////////////////////////////////////////////////
(product[i] = con/(10^(9-i)); //find the current decimal place)

This means for example, if i = 2:

1234567890 / (10 ^ 7) = 123 //the numbers after the decimal point will be forgotten since this is not a float, correct?
///////////////////////////////////////////////////////////////////////////////////
(product[i] = product[i] - product[n] * 10 ^ i;)

Then here, we subtract the 1 and the 2 in the places above the 3, because the only number that should be standing is 3. 3 is the number selected to be added to the char string when i = 2.

n = 0 to < i (0 to 1) in order to subtract the 10's and 100's place before the 3.

Example when n = 0 (and i = 2)

123 = 123 - (1 * 10 ^ 2) = 23

then when n = 1 (i still = 2)

23 = 23 - (2 * 10 ^ 2) = 3
//////////////////////////////////////////////////////////////////////////////////////////////
cString[i] = product[i] + '0';

Finally, the number 3 is given its character value by being added to '0' or 0x30.
//////////////////////////////////////////////////////////////////////////////////////////////

Does this help?
Ah - you've made a common mistake - the ^ operator in C++ is not exponentiation, it is bitwise xor. You need to use std::pow.
OK, thank you, I will work on that.
Topic archived. No new replies allowed.