itoa function converts integer into null-terminated string. It can convert negative numbers too. The standard definition of itoa function is give below:-
The third parameter base specify the conversion base. For example:- if base is 2, then it will convert the integer into its binary compatible string or if base is 16, then it will create hexadecimal converted string form of integer number.
If base is 10 and value is negative, the resulting string is preceded with a minus sign (-). With any other base, value is always considered unsigned.
itoa(1567, str, 10) should return string "1567" itoa(-1567, str, 10) should return string "-1567" itoa(1567, str, 2) should return string "11000011111" itoa(1567, str, 16) should return string "61f"
Individual digits of the given number must be processed and their corresponding characters must be put in the given string. Using repeated division by the given base, we get individual digits from least significant to most significant digit. But in the output, these digits are needed in reverse order. Therefore, we reverse the string obtained after repeated division and return it.
Base:10 1567 Base:10 -1567 Base:2 11000011111 Base:8 3037 Base:16 61f
This article is contributed by Neha Mahajan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Implement Your Own sizeof
- Implement your own tail (Read last n lines of a huge file)
- How to implement our own Vector Class in C++?
- Write your own memcpy() and memmove()
- Write your own strlen() for a long string padded with '\0's
- Making your own Linux Shell in C
- How to write your own header file in C?
- When should we write our own copy constructor?
- Does C++ compiler create default constructor when we write our own?
- When should we write our own assignment operator in C++?
- Implementing own Hash Table with Open Addressing Linear Probing in C++
- How to implement Min Heap using STL?
- Using class to implement Vector Quantities in C++
- How to implement user defined Shared Pointers in C++