[英]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.