将Int转换为Char数组

时间:2012-03-24 01:52:41

标签: c++ char int

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

3 个答案:

答案 0 :(得分: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++;
    }
}

答案 1 :(得分:0)

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

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

......但我不确定这是不是你想要的。

答案 2 :(得分:0)

采用这种限制进行转换的一种可能方式如下:

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

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

相关问题