本题要求实现一个将长整数转化成16进制字符串的简单函数。
函数接口定义:
void f( long int x, char *p );
其中x是待转化的十进制长整数,p指向某个字符数组的首元素。函数f的功能是把转换所得的16进制字符串写入p所指向的数组。16进制的A~F为大写字母。
————————————————
#include<iostream>
#include<cstring>
#include<algorithm>
const int maxn=100;
using namespace std;
void f(long int x,char *p)
{
int k=x;int l=x;int c=0;
if(x==0) *p='0';
else
{
if(k<0) k=-k;
if(l<0) l=-l;
while(k)
{
k/=16;c++;
}
}
for(int i=c-1;i>=0;i--)
{
int a=l%16;
if(a>9)
{
p[i]=a+'A'-10;
}
else p[i]=a+'0';
l/=16;
}
if(x<0) cout<<'-';
}
int main(void)
{
long int x;char str[maxn];
cin>>x;
f(x,str);
cout<<str<<endl;
return 0;
}