2012-03-24 148 views
0

我需要創建一個名爲MyInt的類,它通過創建一個int數組來處理任何大小的正數。我正在製作一個構造函數,用於將int(任何由ints支持的大小)轉換爲MyInt。我需要將int轉換爲char數組,然後逐位讀入int數組。所以我的問題是,不使用除了<iostream><iomanip><cstring>任何庫我如何轉換多個數字一個int到字符數組?將Int轉換爲Char數組

+3

爲什麼你需要轉換爲'char'數組?爲什麼不直接進入最後的'int'數組? – 2012-03-24 01:54:42

+0

我該怎麼做?將int轉換爲int數組? – easyxtarget 2012-03-24 01:58:37

+2

int數組的內容需要是什麼? – 2012-03-24 01:59:23

回答

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 

...但我不完全知道這是你在找什麼。

+0

這不起作用,至少不了解如果我理解這個問題。您的代碼會生成一個字符數組,其中包含一個字符:ASCII值爲30的字符。它不會生成帶有'3'字符,'0'字符和空終止符的字符數組,它是(如果我理解正確)OP想要什麼。 – 2014-01-04 07:33:11

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 

我希望我沒有誤解你的問題,但爲我工作,給我,上面寫着相同的可打印陣列作爲整數本身。

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++; 
    } 
}