-1

My goal is to convert an integer:

int = 1234;

to an array:

int converted[] = {1,2,3,4};

Can you give me a tip what I will need for programming this?

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
manIneedHelp
  • 39
  • 1
  • 1
  • 5

1 Answers1

1

assuming your number is unsigned, you could try the following:

unsigned int i = 1234 ;
char array[5] ;

for(int j=0 ; i>0 ; j++, i/=10)
   array[5-j] = (char)(i%10) ;

If your integer is signed, you would need an extra element in the array and some minor modifications to the code to account for the sign.

If what you want is in fact an array containing the ASCII representations of the digits (e.g. 1234 -> {'1','2','3','4'}), you should replace the last line above with

   array[5-j] = (char)(i%10)+'0' ;
Alphonsos_Pangas
  • 514
  • 1
  • 3
  • 13