【问题标题】:Convert Int to Char Array将 Int 转换为 Char 数组
【发布时间】:2012-03-24 01:52:41
【问题描述】:

我需要创建一个名为 MyInt 的类,它通过创建一个 int 数组来处理任何大小的正数。我正在制作一个构造函数,用于将 int(int 支持的任何大小)转换为 MyInt。我需要将 int 转换为 char 数组,然后逐位读取 int 数组。所以我的问题是,除了<iostream> <iomanip><cstring> 之外不使用任何库,如何将多位整数转换为字符数组?

【问题讨论】:

  • 为什么需要转换成char数组?为什么不直接进入最终的int 数组?
  • 我该怎么做?将 int 转换为 int 数组?
  • int数组的内容需要是什么?
  • 任何更大的数字。比如 987657656344632652457985675637659045635732876499873409427034965563240987 什么的。
  • 您的意思是您想将 int 更改为您的 MyInt,但您的 MyInt 接受 char 序列?那么,需要把int改为char数组,然后用MyInt来构造?如果是这样,我想也许“sprintf”可以帮助你。

标签: c++ char int


【解决方案1】:

您不需要将char 数组作为中间步骤。数字(我假设以 10 为基数)可以使用模 10 运算一一获得。比如:

convert(int *ar, const int i)
{
    int p, tmp;

    tmp = i
    while (tmp != 0)
    {
        ar[p] = tmp % 10;
        tmp   = (tmp - ar[p])/10;
        p++;
    }
}

【讨论】:

    【解决方案2】:

    不确定这是否是您想要的,但是:

    int myInt = 30;
    char *chars = reinterpret_cast<char*>(&myInt);
    

    你可以得到 4 个单独的字符:

    chars[0]; // is the first char
    chars[1]; // is the second char
    chars[2]; // is the third char, and
    chars[3]; // is the fourth/last char
    

    ...但我不完全确定这是否是您正在寻找的。​​p>

    【讨论】:

    • 这不起作用,至少如果我理解这个问题的话。您的代码会生成一个包含一个字符的字符数组:ASCII 值为 30 的字符。它不会生成包含“3”字符、“0”字符和空终止符的字符数组,即(如果我理解正确)OP想要什么。
    【解决方案3】:

    在这种限制下进行转换的一种可能方法如下:

    function convert:
        //find out length of integer (integer division works well)
        //make a char array of a big enough size (including the \0 if you need to print it)
        //use division and modulus to fill in the array one character at a time
        //if you want readable characters, don't forget to adjust for them
        //don't forget to set the null character if you need it
    

    我希望我没有误解你的问题,但这对我有用,给了我一个与整数本身读取相同的可打印数组。

    【讨论】:

      猜你喜欢
      • 2011-11-09
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      • 2014-03-02
      • 2021-10-15
      • 1970-01-01
      • 2011-08-30
      相关资源
      最近更新 更多