I have to convert a decimal number to octal and hexadecimal using bitwise operations. I know how to convert it to binary:
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;
}
May you help me convert from decimal to hexadecimal? What should the basic idea be? Is it possible to use a mask for that? Thank you.
You could “cheat” and use
sprintf:Or, to elaborate on @user1113426’s answer: