十进制到十六进制转换

时间:2018-05-16 16:47:48

标签: c++

我需要编写以下程序: 我有一个很长的非负整数(4字节)。从小于5的十六进制数字中删除。 但我不知道从哪里开始。 我的代码:

#include <iostream>
using namespace std;
int main()
{ 
    unsigned int x=10012;
    char hexString[32];
    cout<<hex<<x<<endl;
    itoa(x,hexString,16);
    cout<<hexString;
    for(int i=0;i<strlen(hexString);i++)
    {
        int a = hexString[i];
        if(a < 5)
        {
            for(int j=i;j<strlen(hexString)-1;j++)
                hexString[j] = hexString[j+1];
                i--;
        }
    }
    cout<<hexString;
    system("pause");
    return 0;
}

2 个答案:

答案 0 :(得分:0)

也许(在黑暗中完全出手导致你的问题很不清楚):

#include <iostream>

using namespace std;

int main()
{ 
    unsigned int x=10012;
    char hexString[32];
    char buf[32] = {};
    sprintf(hexString, "%x", x);
    cout<<"Hex String: "<<hexString<<endl;
    for(int i=0, j=0;i<strlen(hexString);i++)
    {
        // Convert from ASCII value to int
        int a = hexString[i] - '0';
        if(a > 5)
        {
            buf[j] = hexString[i];
            j++;
        }
    }
    cout<<"With nothing greater then five: "<<buf<<endl;
    return 0;
}

答案 1 :(得分:0)

另一种思考问题的方式:根本不使用字符串。

unsigned int filter(unsigned int x)
{
    if(x < 5) // no more digits worth keeping. Time to head back and collect results.
    {
        return 0;
    }
    if (x%16 < 5) // exclude this digit
    {
        return filter(x >> 4); // return what we already have collected
    }
    else //include this number
    {
        return (filter(x >> 4) << 4) + x%16; // make room, collect digit.
    }
}

filter将使用少一个数字(删除最低有效数字)调用自己,直到没有值得收集的数字为止。每次过滤调用都会查看最不重要的数字,并决定通过将其添加到返回途中累积的数字的末尾或拒绝它来保留它。

更明显(并且应该在优化后同样快)

unsigned int filter(unsigned int x)
{
    if (x < 5) // no more digits worth keeping. Time to head back and collect results.
    {
        return 0;
    }
    unsigned int digit = x % 0x10; // isolate least significant hex digit
    unsigned int remaining = x / 0x10; // remove least significant hex digit
    unsigned int collected = filter(remaining); //process remaining input
    if (digit >= 5) // collect this digit
    {
        collected = collected * 0x10 + digit; // make room and add digit.
    }
    return collected;
}