Hello, I need to split an int into a char array so I can use a buzzer to beep the individual digits.
But I cant seem to to turn an int into a char
Thanks.
Hello, I need to split an int into a char array so I can use a buzzer to beep the individual digits.
But I cant seem to to turn an int into a char
Thanks.
You mean you want to print the value into a string? By individual numbers you mean individual decimal digits?
sprintf prints to a string (char array).
char buffer [7] ; // long enough for 16 bit integer, sign, 5 digits and null.
sprintf (buffer, "%i", value) ; // print into buffer
Thanks so much for this, but what does the %i do?
There is a link to the AVR GCC library functions on the reference page on this site. But it should be made much more prominent.
If you want the digits of an int, you are after the division and remainder operations.
In C, division '/' of ints always rounds towards zero. And remainder '%' give you the remainder.
So for a two digit number, x/10 and x%10 give you the two digits.
For a (say) five digit number, the code is
int x = some_number;
for(int i = 10000; i > 0; i /= 10) {
beep((x/i) % 10 ); // zero to 9
}
The sprintf() function is very powerful, but usually you only use a fraction of its functionality. As a result, you end up using more memory than necessary. Consider the following program:
void setup() {
int i;
int val = 32111;
char buffer [7] ; // long enough for 16 bit integer, sign, 5 digits and null.
Serial.begin(9600);
// sprintf (buffer, "%i", val); // print into buffer
itoa(val, buffer, 10); // value, char array, base
for (i = 0; buffer[i]; i++) {
Serial.print(buffer[i]);
Serial.print(" ");
}
}
void loop() {
}
If you comment out the itoa() function call and use sprintf(), the compiled code uses 3298 bytes of memory. As it stand above, the same program compiles to 1938 bytes.