繁体   English   中英

将Int转换为Char数组

[英]Convert Int to Char Array

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

您不需要做一个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++;
    }
}

不知道这是否是您想要的,但是:

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

您可以获取4个单独的char:

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

...但是我不确定是否正是您要的内容。

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

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

我希望我不会误会您的问题,但这对我有用,给了我一个可打印的数组,该数组读取的值与整数本身相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM