strtol 函数:
它的功能是将一个任意1-36进制数转化为10进制数,返回是long int型。
函数为long int strtol(const char *nptr, char **endptr, int base)
base是要转化的数的进制,非法字符会赋值给endptr,nptr是要转化的字符,例如:
- char buffer[20]="10379cend$3";
- char *stop;
- printf("%d\n",strtol(buffer, &stop, 8));
- printf("%s\n", stop);
输出结果:
543
9cend$3
将一个8进制转化为10进制,读取1037,其他后面的为非法字符,转化结果以int型输出来。
另外,如果base为0,且字符串不是以0x(或者0X)开头,则按十进制进行转化。如果base为0或者16,并且字符串以0x(或者0X)开头,那么,x(或者X)被忽略,字符串按16进制转化。如果base不等于0和16,并且字符串以0x(或者0X)开头,那么x被视为非法字符。
最后,需要说明的是,对于nptr指向的字符串,其开头和结尾处的空格被忽视,字符串中间的空格被视为非法字符。
itoa函数:
它的功能是将一个10进制的数转化为n进制的值、其返回值为char型。(和上面的strtol效果相反)
例如:itoa(num, str, 2); num是一个int型的,是要转化的10进制数,str是转化结果,后面的值为目标进制。
- #include<cstdlib>
- #include<cstdio>
- int main()
- {
- int num = 10;
- char str[100];
- itoa(num, str, 2);
- printf("%s\n", str);
- return 0;
- }
输出结果:
1010
除了上面两个,c++中还有一些定向的转换:
std::bitset(转2进制),std::oct(转8进制),std::dec (转10进制),std::hex(转16进制)。
- #include <bitset>
- #include <iostream>
- using namespace std;
- int main()
- {
- cout << "36的8进制:" << std::oct << 36 << endl;
- cout << "36的10进制" << std::dec << 36 << endl;
- cout << "36的16进制:" << std::hex << 36 << endl;
- cout << "36的2进制: " << bitset<8>(36) << endl;
- return 0;
- }
(这里bitset后面尖括号里代表输出的位数)
itoa
char * itoa ( int value, char * str, int base );
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.
str should be an array long enough to contain any possible value: (sizeof(int)*8+1) for radix=2, i.e. 17 bytes in 16-bits platforms and 33 in 32-bits platforms.
Parameters
-
value
- Value to be converted to a string. str
- Array in memory where to store the resulting null-terminated string. base
- Numerical base used to represent the value as a string, between 2 and 36, where 10 means decimal base, 16hexadecimal, 8 octal, and 2 binary.
Return Value
A pointer to the resulting null-terminated string, same as parameter str.Portability
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.A standard-compliant alternative for some cases may be sprintf:
- sprintf(str,"%d",value) converts to decimal base.
- sprintf(str,"%x",value) converts to hexadecimal base.
- sprintf(str,"%o",value) converts to octal base.
Example
|
|
Output:
Enter a number: 1750 decimal: 1750 hexadecimal: 6d6 binary: 11011010110 |
See also
-
sprintf
- Write formatted data to string (function )
-
atoi
- Convert string to integer (function )
-
atol
- Convert string to long integer (function )