【问题标题】:C++ base conversionC++ 基础转换
【发布时间】:2010-07-11 23:56:53
【问题描述】:

您好,我正在尝试将一些代码从 Windows 移植到 Linux。我有这个:

itoa(word,aux,2);

但 GCC 无法识别 itoa。如何以 C++ 方式将这种转换为 base 2?

谢谢 ;)

【问题讨论】:

  • 不,gcc 无法识别 itoa。您可以从命名 word,aux,2 的类型开始
  • How would I convert decimal into binary?。它专门关于在 C++ 中将整数格式化为二进制字符串。 Necrolis 的解决方案实际上返回一个字符串(而不是打印到 cout)。

标签: c++ base


【解决方案1】:

Here´s 一些帮助

/* itoa:  convert n to characters in s */
 void itoa(int n, char s[])
 {
     int i, sign;

     if ((sign = n) < 0)  /* record sign */
         n = -n;          /* make n positive */
     i = 0;
     do {       /* generate digits in reverse order */
         s[i++] = n % 10 + '0';   /* get next digit */
     } while ((n /= 10) > 0);     /* delete it */
     if (sign < 0)
         s[i++] = '-';
     s[i] = '\0';
     reverse(s);
 }

你应该根据你的需要调整它(注意这个有 2 个参数,而不是 3 个) 另请注意,反向功能也在维基百科链接中。

此外,here 是其他一些情况(但不适用于 base 2)

此函数未在 ANSI-C 中定义 并且不是 C++ 的一部分,而是 一些编译器支持。

符合标准的替代方案 有些情况可能是 sprintf:

sprintf(str,"%d",value) 转换为十进制。

sprintf(str,"%x",value) 转换为十六进制。

sprintf(str,"%o",value) 转换为八进制。

【讨论】:

    【解决方案2】:

    这是 Tom 的答案,已修改为根据您的代码要求使用基础:

    void itoa(int n, char s[], std::size_t base = 10) {
        const char digits[] = "0123456789abcdef";
        int i, sign;
    
        if (base < 2 || base > 16)
            throw std::invalid_argument("invalid base");
        if ((sign = n) < 0)  /* record sign */
            n = -n;      /* make n positive */
        i = 0;
        do {       /* generate digits in reverse order */
            s[i++] = digits[n % base]; /* get next digit */
        } while ((n /= base) > 0);         /* delete it */
        if (sign < 0)
            s[i++] = '-';
        s[i] = '\0';
        reverse(s);
    }
    

    【讨论】:

      【解决方案3】:

      有一页itoa实现here

      【讨论】:

        【解决方案4】:

        【讨论】:

        【解决方案5】:

        如何使用递归的力量? :)

        int convert_base(int v, int b){ 
        
            if (v == 0) return 0;   
            else 
                return (v%b+10*convert_base(v/b,b));    
        }
        

        【讨论】:

          猜你喜欢
          • 2016-04-07
          • 2017-01-20
          • 2017-03-26
          • 1970-01-01
          • 2014-04-21
          • 2018-06-06
          • 1970-01-01
          • 1970-01-01
          • 2013-10-22
          相关资源
          最近更新 更多