Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

celia

macrumors newbie
Original poster
Jun 24, 2007
8
0
Hi,

I want to convert an array of ints - into one long string with ':' (semicolon) between each int.

How to go about it?


Thanks.
 

celia

macrumors newbie
Original poster
Jun 24, 2007
8
0
Language

It's in C.

Thanks dejo for correcting. It's colon.:eek:
 

GothicChess.Com

macrumors regular
Apr 6, 2007
126
0
Philadelphia, PA
Here's a quick-n-dirty way to do it in C (I didn't compile it...)

Code:
void convert_ints_to_string(void)
{
	#define k_maximum_characters_for_demo 160
	const int k_base_10 = 10;
	unsigned short loop;
	unsigned short length_of_string = 0;
	int sample_array[7];
	char your_output_as_a_C_string[k_maximum_characters_for_demo];
	char intermediate_string[20];
	
	sample_array[0] = 42;
	sample_array[1] = -209;
	sample_array[2] = 3287;
	sample_array[3] = 0;
	sample_array[4] = 291;
	sample_array[5] = -2323;
	sample_array[6] = -2323;
	
	for(loop = 1; loop <= 7; loop++)
	{
		/**********************************************************************************/
		/* take the element in the array, an int, and turn it into as ASCII string.        */
		/* itoa = INT to ASCII, 3 parameters, the int, the string receptacle, and the base */
		/**********************************************************************************/
		
		itoa(sample_array[loop-1], intermediate_string, k_base_10);
		
		length_of_string += strlen(intermediate_string);
		
		/*****************************************************************************/
		/* reserved 160 characters in the string array, make sure it is not exceeded */
		/*****************************************************************************/
		if(length_of_string > k_maximum_characters_for_demo) exit(0);
		
		your_output_as_a_C_string = strcat(your_output_as_a_C_string , intermediate_string, ":" );
		
		/******************************************************/
		/* add one to our count since we just added the colon */
		/******************************************************/
		length_of_string++;
		if(length_of_string > k_maximum_characters_for_demo) exit(0);
	}
	
	/********************************************************************************/
	/* all c strings are terminated with a NULL character, signified by backslash 0 */
	/********************************************************************************/
	your_output_as_a_C_string = strcat(your_output_as_a_C_string, '\0' );
	
}
 

HiRez

macrumors 603
Jan 6, 2004
6,250
2,576
Western US
This is why I love Python:
Code:
joined_string = ":".join(sample_array)
Done. No loops. No explicit temporary strings. No counter variables. No range checks.

I know, not useful to the discussion, but still. :rolleyes:
 

GothicChess.Com

macrumors regular
Apr 6, 2007
126
0
Philadelphia, PA
Just as a side note...

I can't remember in C if you need to put a single character in single quotes when concatenating, like ':' instead of double quotes like I showed, ":"...

...I just thought of this because the \0 at the end of the C string must be surrounded by the single quotes, like '\0'
 

celia

macrumors newbie
Original poster
Jun 24, 2007
8
0
Final compiled code

HTML:
#define k_maximum_characters_for_demo 10


main()
{

	const int k_base_10 = 10;
	unsigned short loop;
	unsigned short length_of_string = 0;
	int sample_array[3] = {0x21,0x3a,0x45};
	char your_output_as_a_C_string[k_maximum_characters_for_demo] =" ";
	char intermediate_string[2];
	
	
	for(loop = 0; loop < 3; loop++)
	{
		/**********************************************************************************/
		/* take the element in the array, an int, and turn it into as hex string.        */
				/**********************************************************************************/
		
		sprintf( intermediate_string, "%x", sample_array[loop] );

		length_of_string += strlen(intermediate_string);
		
		/*****************************************************************************/
		/* reserved 160 characters in the string array, make sure it is not exceeded */
		/*****************************************************************************/
		if(length_of_string > k_maximum_characters_for_demo) exit(0);

		 strcat(intermediate_string,":");
		 strcat(your_output_as_a_C_string,intermediate_string);

		/******************************************************/
		/* add one to our count since we just added the colon */
		/******************************************************/
		length_of_string++;
		if(length_of_string > k_maximum_characters_for_demo) exit(0);
	}
	/********************************************************************************/
	/* all c strings are terminated with a NULL character, signified by backslash 0 */
	/********************************************************************************/
	printf("%s", strcat(your_output_as_a_C_string, "\0" ));
}

sprintf can be helpful if the array value has to be retained (only type has to change).

Thanks everyone.
 

lazydog

macrumors 6502a
Sep 3, 2005
709
6
Cramlington, UK
Hi

Work out how big the final string is going to be 1st:-

Code:
char temp[ 32 ] ;
int size = 0 ;
	
for ( int i = 0 ; i < ARRAY_SIZE ; ++ i )
{
   sprintf( temp, "%d", test_array[ i ] ) ;
   size += strlen( temp ) + 1 ;	// +1 is for the colon
}

then allocate the memory for it:-

Code:
char* str = (char *) malloc( size ) ; // Last ':' will be overwritten with \0

Then create the string:-

Code:
int offset = 0 ;
for ( int i = 0 ; i < TEST_SIZE - 1 ; ++ i )
{
   sprintf( temp, "%d:", test_array[ i ] ) ;
   strcpy( str + offset, temp ) ;
   offset += strlen( temp ) ;
}

//
// Last number doesn't need a colon.
//
sprintf( temp, "%d", test_array[ TEST_SIZE - 1 ] ) ;
strcpy( str + offset, temp ) ;

That should do it!

b e n
 

GothicChess.Com

macrumors regular
Apr 6, 2007
126
0
Philadelphia, PA
Hi

Work out how big the final string is going to be 1st:-

...

then allocate the memory for it

...

Then create the string

...

That should do it!

b e n


I didn't want to inundate her on the first iteration with a high performance demo. It seemed the question was more centered on loop-handling, arrays, and num-to-string conversions. I could have spawned a high-performance version of the thing in only 5 lines of code that would be nearly impossible to decipher. For example, look at this code, which is an actual fully-functional OS if you have a boot loader :)

Code:
#define G(n) int n(int t, int q, int d)
#define X(p,t,s) (p>=t&&p<(t+s)&&(p-(t)&1023)<(s&1023))
#define U(m) *((signed char *)(m))
#define F if(!--q){
#define I(s) (int)main-(int)s
#define P(s,c,k) for(h=0; h>>14==0; h+=129)Y(16*c+h/1024+Y(V+36))&128>>(h&7)?U(s+(h&15367))=k:k

G (B)
{
  Z;
  F D = E (Y (V), C = E (Y (V), Y (t + 4) + 3, 4, 0), 2, 0);
  Y (t + 12) = Y (t + 20) = i;
  Y (t + 24) = 1;
  Y (t + 28) = t;
  Y (t + 16) = 442890;
  Y (t + 28) = d = E (Y (V), s = D * 8 + 1664, 1, 0);
  for (p = 0; j < s; j++, p++)
    U (d + j) = i == D | j < p ? p--, 0 : (n = U (C + 512 + i++)) < ' ' ? p |=
      n * 56 - 497, 0 : n;
}

n = Y (Y (t + 4)) & 1;
F
U (Y (t + 28) + 1536) |=
62 & -n;
M
U (d + D) =
X (D, Y (t + 12) + 26628, 412162) ? X (D, Y (t + 12) + 27653,
				       410112) ? 31 : 0 : U (d + D);
for (; j < 12800; j += 8)
  P (d + 27653 + Y (t + 12) + ' ' * (j & ~511) + j % 512,
     U (Y (t + 28) + j / 8 + 64 * Y (t + 20)), 0);
}

F if (n)
  {
    D = Y (t + 28);
    if (d - 10)
      U (++Y (t + 24) + D + 1535) = d;
    else
      {
	for (i = D; i < D + 1600; i++)
	  U (i) = U (i + 64);
	Y (t + 24) = 1;
	E (Y (V), i - 127, 3, 0);
      }
  }
else
  Y (t + 20) += ((d >> 4) ^ (d >> 5)) - 3;
}
}

G (_);
G (o);
G (main)
{
  Z, k = K;
  if (!t)
    {
      Y (V) = V + 208 - (I (_));
      L (209, 223) L (168, 0) L (212, 244) _((int) &s, 3, 0);
      for (; 1;)
	R n = Y (V - 12);
      if (C & ' ')
	{
	  k++;
	  k %= 3;
	  if (k < 2)
	    {
	      Y (j) -= p;
	      Y (j) += p += U (&D) * (1 - k * 1025);
	      if (k)
		goto y;
	    }
	  else
	    {
	      for (C = V - 20;
		   !i && D & 1 && n
		   && (X (p, Y (n + 12), Y (n + 16)) ? j = n + 12, Y (C + 8) =
		       Y (n + 8), Y (n + 8) = Y (V - 12), Y (V - 12) =
		       n, 0 : n); C = n, n = Y (n + 8));
	      i = D & 1;
	      j &= -i;
	    }
	}
      else if (128 & ~D)
	{
	  E (Y (n), n, 3, U (V + D % 64 + 131) ^ 32);
	  n = Y (V - 12);
	y:C = 1 << 24;
	  M U (C + D) = 125;
	  o (n, 0, C);
	  P (C + p - 8196, 88, 0);
	  M U (Y (0x11028) + D) = U (C + D);
	}
    }
}

for (D = 720; D > -3888; D--)
  putchar (D >
	   0 ?
	   "  )!\320\234\360\256\370\256 0\230F           .,mnbvcxz    ;lkjhgfdsa \n][poiuytrewq  =-0987654321   \357\262   \337\337 \357\272   \337\337         ( )\"\343\312F\320!/ !\230 26!/\16 K>!/\16\332 \4\16\251\0160\355&\2271\20\2300\355`x{0\355\347\2560 \237qpa%\231o!\230 \337\337\337     ,               )\"K\240   \343\316qrpxzy\0 sRDh\16\313\212u\343\314qrzy    !0( "
	   [D] ^ 32 : Y (I (D)));
return 0;
}

G (o)
{
  Z;
  if (t)
    {
      C = Y (t + 12);
      j = Y (t + 16);
      o (Y (t + 8), 0, d);
      M U (d + D) =
	X (D, C, j) ? X (D, C + 1025, j - 2050) ? X (D, C + 2050,
						     j - 3075) ? X (D,
								    C + 2050,
								    j -
								    4100) ?
	X (D, C + 4100,
	   ((j & 1023) + 18424)) ? 176 : 24 : 20 : 28 : 0 : U (d + D);
      for (n = Y (t + 4); U (i + n); i++)
	P (d + Y (t + 12) + 5126 + i * 8, U (n + i), 31);
      E (Y (t), t, 2, d);
    }
}

G (_)
{
  Z = Y (V + 24);
  F Y (V - 16) += t;
  D = Y (V - 16) - t;
}

F for (i = 124; i < 135; i++)
  D = D << 3 | Y (t + i) & 7;
}

if (q > 0)
  {
    for (; n = U (D + i); i++)
      if (n - U (t + i))
	{
	  D += _(D, 2, 0) + 1023 & ~511;
	  i = ~0;
	}
    F if (Y (D))
      {
	n = _(164, 1, 0);
	Y (n + 8) = Y (V - 12);
	Y (V - 12) = n;
	Y (n + 4) = i = n + 64;
	for (; j < 96; j++)
	  Y (i + j) = Y (t + j);
	i = D + 512;
	j = i + Y (i + 32);
	for (; Y (j + 12) != Y (i + 24); j += 40);
	E (Y (n) = Y (j + 16) + i, n, 1, 0);
      }
  }
}

return D;
}

It will compile and run with no errors, and it actually does something!
 

toddburch

macrumors 6502a
Dec 4, 2006
748
0
Katy, Texas
Code:
#define G(n) int n(int t, int q, int d)
#define X(p,t,s) (p>=t&&p<(t+s)&&(p-(t)&1023)<(s&1023))
#define U(m) *((signed char *)(m))
#define F if(!--q){
#define I(s) (int)main-(int)s
#define P(s,c,k) for(h=0; h>>14==0; h+=129)Y(16*c+h/1024+Y(V+36))&128>>(h&7)?U(s+(h&15367))=k:k

G (B)
{
  Z;
  F D = E (Y (V), C = E (Y (V), Y (t + 4) + 3, 4, 0), 2, 0);
  Y (t + 12) = Y (t + 20) = i;
  Y (t + 24) = 1;
  Y (t + 28) = t;
  Y (t + 16) = 442890;

....


for (; Y (j + 12) != Y (i + 24); j += 40);
	E (Y (n) = Y (j + 16) + i, n, 1, 0);
      }
  }
}

return D;
}

It will compile and run with no errors, and it actually does something!

Looks like some of the code I have to wade through on a daily basis... only difference is that it's not assembler! BLLLAAAHHK!

Todd
 

iSee

macrumors 68040
Oct 25, 2004
3,539
272
That code won't compile and run.
Where is that Z used near the top defined? On the next line, I don't think D is defined either.
 

GothicChess.Com

macrumors regular
Apr 6, 2007
126
0
Philadelphia, PA
Are you saying you're the author of this?
b e n

It was an example, you know, like other people post from time-to-time, like HiRez:

This is why I love Python:
Code:
joined_string = ":".join(sample_array)

I said I had worked on an OS before, so I have many examples of such from way-back-when. The point was: there are ways to code that are complex, and there are ways to code that are easy to understand.
 

longofest

Editor emeritus
Jul 10, 2003
2,925
1,693
Falls Church, VA
hey guys.

Seen a lot of good suggestions, but they are all implemented in a serial fashion, and doesn't take advantage of parallelism. While I know the question was a basic question, it can't be too early to start learning good habits for coding in parallel.

I'm kinda busy, so I won't actually write out code, but here's the idea (sorry for some C++ style pseudo-coding):
Code:
//globally accessible integer array
int myArray[foo] = {1,2,3,...,bar};

int main()
{
string string1, string2;

//spawn worker 1 thread
fork worker1(&string2);  

for(int i=0; i = foo/2; i++)
{
 string1.append(itoa(myArray[i]));
 string1.append(':');
}

//wait for worker1 to exit
join worker1;  

string1.append(string2);

//string1 now has everything you need.

return 0;
}

worker1(&string2)
{
for(int i=foo/2; i=foo; i++)
{
 string2.append(itoa(myArray[i]));
 string2.append(:);
}

return 0;
}

Real parallel programing would be better done than that, as it would contain logic to see how many processors you have and then spawn the appropriate number of threads to maximize performance. However, you get the idea.
 

longofest

Editor emeritus
Jul 10, 2003
2,925
1,693
Falls Church, VA
How big is the array that you are considering multithreading?

I don't know, but note the following...

While I know the question was a basic question, it can't be too early to start learning good habits for coding in parallel.

Being that a majority of programmers today don't consider parallelism when programming, I'm just trying to raise awareness. Not necessarily saying it would be a good thing to do in this case (i.e. if the array was really small to begin with, the overhead of spawning a thread wouldn't be worth the gains).
 

lazydog

macrumors 6502a
Sep 3, 2005
709
6
Cramlington, UK
Hi Celia

I'm not sure if you are finished with this thread or not, but looking at your 'final code' I can see a few things that might cause you some problems:-

Code:
char intermediate_string[2];

This should be:-

Code:
char intermediate_string[4];

because it needs to hold 3 character length strings, ie "21:" "3a:" and "45:" (don't forget the terminating \0 needs a space too).


Code:
#define k_maximum_characters_for_demo 10
…
char your_output_as_a_C_string[k_maximum_characters_for_demo] =" ";

These two lines should be:-

Code:
#define k_maximum_characters_for_demo 10
…
char your_output_as_a_C_string[k_maximum_characters_for_demo+1] ="";

Again you need +1 because of the terminating \0 present in strings. Either that or in the rest of your code you would need to change your tests to:-

Code:
if(length_of_string > k_maximum_characters_for_demo - 1)

You're absolutely right about adding an initialisation string to your_output_as_aC_string. Without it the contents would be garbage and the first strcat() to it would produce unpredictable results. However ="" would have been sufficient unless you really wanted a space as the first character.

Finally

Code:
printf("%s", strcat(your_output_as_a_C_string, "\0" ));

the last strcat is not needed. strcat() appends a \0 for you automatically.

Hope this helps

b e n
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.