//写一个函数实现8进制字符串到16进制字符串的转换
//例如:
//输入"755"结果是"1ED"
//输入"777777777777"结果是"FFFFFFFFF" (注意超过了32位)
//答案1
//C99的标准支持long long类型,能满足超过32位的数据小于64位的数据
#include <iostream.h>
#include <string.h>
//8进制字符串转16进制字符串
//注:要保证pHexStr指向内存空间的长度
bool ConvertOctalStrToHexStr(const char* pOctalStr, char* pHexStr)
{
int nNum = 0;
int nLength = 0; //保存8进制字符串的长度
int nHexCount = -1; //保存16进制数的位数
int nRemainder = 0; //保存余数
char* pHexNumStr = NULL;
long long int64DecNum = 0; //10进制64位数
long long int64TmpNum = 0;
//检查
if (pOctalStr == NULL || pHexStr == NULL)
{
return false;
}
//获取8进制字符串的长度
nLength = strlen(pOctalStr);
//8进制数转10进制
for (int i = nLength - 1; i >= 0 ; i--)
{
//8进制的数必须在0~7之间
if (pOctalStr[i] < '0' || pOctalStr[i] > '7')
{
return false;
}
//求8的n次方
int64TmpNum = 1;
for (int j = 0; j < nLength-i-1; j++)
{
int64TmpNum *= 8;
}
//字符转数据如,'0'->0
nNum = pOctalStr[i] - 48;
int64DecNum += nNum*int64TmpNum;
}
//申请内存空间放16进制数的字符串
pHexNumStr = new char[nLength];
if (pHexNumStr == NULL)
{
return false;
}
//清零
memset(pHexNumStr, 0, nLength);
//10进制转16进制
while (true)
{
nHexCount++;
nRemainder = int64DecNum % 16;
if (nRemainder >= 0 && nRemainder <= 9)
{
nRemainder += 48;
}
if (nRemainder >= 10 && nRemainder <= 15)
{
nRemainder += 55;
}
pHexNumStr[nHexCount] = nRemainder;
int64DecNum /= 16;
if (int64DecNum == 0)
{
break;
}
}
for (int k = 0; k <= nHexCount; k++)
{
pHexStr[k] = pHexNumStr[nHexCount - k];
}
//释放内存空间
if (pHexNumStr != NULL)
{
delete[] pHexNumStr;
pHexNumStr = NULL;
}
return true;
}
int main(int argc, char* argv[])
{
const char* pszOctrl = "755";
char szHexBuffer[10] = {0};
if (ConvertOctalStrToHexStr(pszOctrl, szHexBuffer) == false)
{
printf("Convert false");
}
else
{
printf("%s
", szHexBuffer);
}
return 0;
}