[英]C: Convert from decimal to hexadecimal using bitwise operations
我必須使用按位運算將十進制數轉換為八進制和十六進制。 我知道如何將其轉換為二進制文件:
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;
}
您能幫我從十進制轉換為十六進制嗎? 基本思想應該是什么? 可以使用口罩嗎? 謝謝。
您可以“作弊”並使用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;
}
我不太懂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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.