我的十进制到十六进制转换函数只适用于正数

My decimal to hex conversion function only woks with positive nums

我在使用以下函数将负数从十进制转换为十六进制时遇到问题:

#include <stdio.h>
 
int main()
{
    int quotient, remainder;
    int i, j = 0;
    char hexadecimalnum[100];
 
    quotient = -50;
 
    while (quotient != 0)
    {
        remainder = quotient % 16;
        if (remainder < 10)
            hexadecimalnum[j++] = 48 + remainder;
        else
            hexadecimalnum[j++] = 55 + remainder;
        quotient = quotient / 16;
    }

    strrev(hexadecimalnum);

    printf("%s", hexadecimalnum);
    return 0;
}

对于quotient = -50;正确的输出应该是:

ffffffce

但是这个函数的输出是:

.

对于正数,输出总是正确的,但对于负数则不然。

我很难理解为什么它不适用于负数。

您可以使用 printf 的格式说明符 "%08x",然后您可以打印各自十六进制表示形式的任何数字。

#include <stdio.h>

void num_to_hex(int a, char *ptr) { snprintf(ptr, 9, "%08x", a); }

int main() {
    char hex[10] = {};
    num_to_hex(-50, hex);
    printf("%s\n", hex);
    return 0;
}

输出:

ffffffce

一些修复:

  • unsigned int quotient - 您需要将 -50 转换为二进制补码中的大十六进制数,否则您将在循环中得到错误的迭代次数 (2),而不是所需的 8 .
  • 删除“幻数”:'0' + remainder'A' + remainder - 10
  • 零初始化 hexadecimalnum 因为它需要在从那里打印字符串之前以 null 终止。更好的是,显式添加空终止。
  • 尽可能使用 for 循环。
  • 还不如把字符从后往前存储,省去额外的字符串反转调用

结果:

#include <stdio.h>

// 4 bytes*2 = 8 nibbles
#define HEX_STRLEN (sizeof(int)*2) 
 
int main()
{
    unsigned int remainder;
    int i = 0;
    char hex[100];
 
    for(unsigned int q = -50; q!=0; q/=16)
    {
      remainder = q % 16;
      if (remainder < 10)
        hex[HEX_STRLEN-i-1] = '0' + remainder;
      else
        hex[HEX_STRLEN-i-1] = 'A' + remainder - 10;
      i++;
    }
    hex[HEX_STRLEN] = '[=10=]'; // explict null termination
    printf("%s\n", hex);
}

(还有很多地方可以改进,这只是初稿。)