Hello,
I tried the following code but it doens't work:
Serial.begin(9600);
int v=3689;
char str[4];
sprintf(str, "%c", v);
byte a=str[0].toInt(); //"3" to 3
Serial.println(a+1); //I should get 3+1=4
Hello,
I tried the following code but it doens't work:
Serial.begin(9600);
int v=3689;
char str[4];
sprintf(str, "%c", v);
byte a=str[0].toInt(); //"3" to 3
Serial.println(a+1); //I should get 3+1=4
You can't do .toInt() on a C-string... It's also not a char to int conversion, it's a ASCII to int conversion. And for a single digit it's simple:
char test[] = "3689";
Serial.println(test[0] - '0');
Just subtract the ASCII value for 0 ![]()
Ah ok, yes it's better like that ![]()
By the way, is there another way to spread all the numbers of an integer (without using strings/char) in a array of bytes like in the following?
int v=3689;
......
print(t[0]); //=3
print(t[1]); //=6
print(t[2]); //=8
print(t[3]); //=9
So you mean from int to ASCII? Yeah, itoa() ![]()
char t[5];
int v = 3689;
itoa(v, t, 10);
Note, this will also NULL terminate the string so we need a string of size 5.
Note2, it does not check if it fits. So trying to put 7531451 into t (with size 5) will just corrupt memory.
Wally06:
By the way, is there another way to spread all the numbers of an integer (without using strings/char)
Yes, you can easily decompose an integer into its digits by simple div and mod calculations. For example:
int digit;
int v = 3689;
while (v != 0 ) {
digit = v % 10;
v /= 10;
printf("%d\n",digit); // Edit: Should be Serial.println(digit);
}
stuart0:
Yes, you can easily decompose an integer into its digits by simple div and mod calculations.
But then use printf() again? Heh? printf() to convert it to ASCII is already a bazooka on a mosquito...
septillion:
But then use printf() again? Heh? printf() to convert it to ASCII is already a bazooka on a mosquito...
The example prints out the digits simply to show how it works. What the op ultimately wants to do with the individual digits is anyone's guess.
Yes I forgot what forum I was on and should have used Serial.println(), but the printing part is actually irrelevant to the example.
Ah, yeah, a computer C++ part. I read it as sprintf() because printf() doesn't do anything on an Arduino.
I tried all your ideas and they all work ![]()
Thanks everybody!