C:使用按位运算从十进制转换为十六进制

时间:2012-03-18 14:31:58

标签: c

我必须使用按位运算将十进制数转换为八进制和十六进制。我知道如何将其转换为二进制文件:

char * decToBin(int n)
{
    unsigned int mask=128;
    char *converted;
    converted=(char *) malloc((log((double) mask)/log((double) 2))*sizeof(char)+2);
    strcpy(converted,"");

    while(mask > 0)
    {
        if(mask & n)
            strcat(converted,"1");
        else
            strcat(converted,"0");

        mask >>= 1;

    }

    return converted;
}  

你可以帮助我从十进制转换为十六进制吗?基本想法应该是什么?是否有可能使用面具?谢谢。

2 个答案:

答案 0 :(得分:3)

你可以“作弊”并使用sprintf

char *conv = calloc(1, sizeof(unsigned) * 2 + 3); // each byte is 2 characters in hex, and 2 characters for the 0x and 1 character for the trailing NUL
sprintf(conv, "0x%X", (unsigned) input);
return conv;

或者,详细说明@ user1113426的答案:

char *decToHex(unsigned input)
{
    char *output = malloc(sizeof(unsigned) * 2 + 3);
    strcpy(output, "0x00000000");

    static char HEX[] = "0123456789ABCDEF";

    // represents the end of the string.
    int index = 9;

    while (input > 0 ) {
        output[index--] = HEX[(input & 0xF)];
        input >>= 4;            
    }

    return output;
}

答案 1 :(得分:1)

我不熟悉C语言,但你可以使用这个伪代码:

char * decToHex(int n){
     char *CHARS = "0123456789ABCDEF";
     //Initialization of 'converted' object
     while(n > 0)
     {      
        //Prepend (CHARS[n & 0xF]) char to converted;
        n >>= 4;
     }
     //return 'converted' object
}