【问题标题】:Converting int digit into hex char - C programming将 int 数字转换为 hex char - C 编程
【发布时间】:2020-04-15 01:41:56
【问题描述】:

这是我将 int 最多 15 转换为十六进制 char 的代码:

static char intToHex(int i)
{
    switch (i)
    {
    case 0:
        return '0';
    case 1:
        return '1';
    case 2:
        return '2';
    case 3:
        return '3';
    case 4:
        return '4';
    case 5:
        return '5';
    case 6:
        return '6';
    case 7:
        return '7';
    case 8:
        return '8';
    case 9:
        return '9';
    case 10:
        return 'a';
    case 11:
        return 'b';
    case 12:
        return 'c';
    case 13:
        return 'd';
    case 14:
        return 'e';
    case 15:
        return 'f';
    default:
        break;
    }
}

有没有办法写得更好,没有这么多的开关案例?

我尝试了什么:

char * returnHex(int i) {

    char * hex = malloc(5);

    sprintf(hex, "%x", i);
    puts(hex);

    return hex; 
}

但这会返回一个 char 数组,而不是我需要的 char。 谢谢!

【问题讨论】:

  • "0123456789abcdef"[i]
  • 或者,i["0123456789abcdef"] :-)
  • 那是一条线:return (unsigned)i < 16 ? "0123456789abcdef"[i] : '\0';

标签: c int hex


【解决方案1】:

另一种方式:

char intToHex(int i)
{
    return (i < 10) : '0' + i : 'a' + i - 10;
}

【讨论】:

    【解决方案2】:

    只需声明一个字符数组,如

    const char hex[] = "0123456789abcdef";
    

    并使用

    if ( i < sizeof( hex ) - 1 )
    {
        return hex[i];
    }
    else
    {
        return hex[0];  // or ant other value
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-01
      • 2015-07-11
      • 2013-10-01
      • 2019-06-13
      • 2020-03-01
      • 2011-07-03
      • 2012-01-16
      • 2023-04-04
      • 2015-12-18
      相关资源
      最近更新 更多