转自:http://blog.csdn.net/xiaofei2010/article/details/7434737
十进制转二进制:
[cpp] view
plaincopyprint?
- //十进制转二进制
- #include<iostream>
- using namespace std;
- void printbinary(const unsigned int val)
- {
- for(int i = 16; i >= 0; i--)
- {
- if(val & (1 << i))
- cout << "1";
- else
- cout << "0";
- }
- }
- int main()
- {
- printbinary(1024);
- return 0;
- }
十进制转八进制
[cpp] view
plaincopyprint?
- //十进制转八进制
- #include <iostream>
- #include <vector>
- using namespace std;
- int main()
- {
- cout<<"input a number:"<<endl;
- int d;
- vector<int> vec;
- cin>>d;
- while (d)
- {
- vec.push_back(d%8);
- d=d/8;
- }
- cout<<"the result is:"<<endl;
- for(vector<int>::iterator ip=vec.end()-1;ip>=vec.begin();)
- {
- cout<<*ip--;
- }
- cout<<endl;
- return 0;
- }
十进制转任意进制:
[cpp] view
plaincopyprint?
- //十进制转换为任意进制的源码
- #include <iostream>
- using namespace std;
- int main()
- {
- long n;
- int p,c,m=0,s[100];
- cout<<"输入要转换的数字:"<<endl;
- cin>>n;
- cout<<"输入要转换的进制:"<<endl;
- cin>>p;
- cout<<"("<<n<<")10="<<"(";
- while (n!=0)//数制转换,结果存入数组s[m]
- {
- c=n%p;
- n=n/p;
- m++;s[m]=c; //将余数按顺序存入数组s[m]中
- }
- for(int k=m;k>=1;k--)//输出转换后的序列
- {
- if(s[k]>=10) //若为十六进制等则输出相对应的字母
- cout<<(char)(s[k]+55);
- else //否则直接输出数字
- cout<<s[k];
- }
- cout<<")"<<p<<endl;
- return 0;
- }
通过库函数实现八进制、十六进制输出:
[cpp] view
plaincopyprint?
- #include <iostream>
- using namespace std;
- int main()
- {
- int test=64;
- cout<<"DEC:"<<test<<endl;
- cout<<"OCT:"<<oct<<test<<endl;//八进制
- cout<<"HEX:"<<hex<<test<<endl;//十六进制
- return 0;
- }
时间: 2024-09-21 02:07:49