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

问题描述 投票:0回答:2

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

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;
}  

愿你帮我从十进制转换为十六进制?应该采取什么基本的想法是什么?是否有可能使用该口罩?谢谢。

c
2个回答
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
投票

我不是精通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
}
© www.soinside.com 2019 - 2024. All rights reserved.