Numbers to string
Posted: Wed Feb 19, 2014 11:17 pm
Hello, how do I convert a number to a string. I want a function like printf() or itoa().
The Place to Start for Operating System Developers
http://forum.osdev.org./
Code: Select all
int i = 8192;
to
char s[] = "8192";
You mean you want to assembly code of itoa()? You can use a debugger to see it. Just put a breakpoint at the function call in C and then step into it.teodori wrote:Hello, how do I convert a number to a string. I want a function like printf() or itoa().
Code: Select all
void string_reverse(uint8_t* string, uint64_t length){
uint8_t ch;
uint64_t i, j;
for(i = 0, j = (length - 1); i < j; i++, j--){
ch = string[i];
string[i] = string[j];
string[j] = ch;
}
}
void string_from_uint64_dec(uint64_t n, uint8_t* string){
uint8_t i = 0;
do{
string[i++] = n % 10 + '0';
}while( (n /= 10) > 0);
string[i] = '\0';
string_reverse(string, string_length(string));
}
void string_from_int64_dec(int64_t n, uint8_t* string){
uint8_t i = 0, sign;
if(n < 0){
sign = 1;
n = -n;
}else
sign = 0;
do{
string[i++] = n % 10 + '0';
}while( (n /= 10) > 0);
if(sign)
string[i++] = '-';
string[i] = '\0';
string_reverse(string, string_length(string));
}
void string_from_uint64_hex(uint64_t n, uint8_t* string){
uint8_t i = 0, c;
do{
c = n % 0x10;
if(c > 9)
string[i++] = c + '0' + 7;
else
string[i++] = c + '0';
}while( (n /= 0x10) > 0);
string[i++] = 'x';
string[i++] = '0';
string[i] = '\0';
string_reverse(string, string_length(string));
}
void string_from_int64_hex(int64_t n, uint8_t* string){
uint8_t i = 0, c, sign;
if(n < 0){
sign = 1;
n = -n;
}else
sign = 0;
do{
c = n % 0x10;
if(c > 9)
string[i++] = c + '0' + 7;
else
string[i++] = c + '0';
}while( (n /= 0x10) > 0);
string[i++] = 'x';
string[i++] = '0';
if(sign)
string[i++] = '-';
string[i] = '\0';
string_reverse(string, string_length(string));
}
At first glance, those look like they should work, but do you plan to write another pair of functions when you want to convert to octal? Then again for binary?teodori wrote:Hello, after searching a bit on google I found and modified some code. Here are my functions: