0

I was thinking what the best way would be to convert a integer array, for example

int array[] = {0x53,0x74,0x61,0x63,0x6B,0x4F,0x76,0x65,0x72,0x66,0x6C,0x6F,0x77,0x00}

to a string, the above integer array is the equivalent of:

int array[] = {'S','t','a','c','k','O','v','e','r','f','l','o','w',0}

so a resulting string would be

std::string so("StackOverflow");

I was thinking of looping through eacht element with foreach and adding it to the string by casting it to char, but I'm wondering if there are cleaner / faster / neater ways to do this?

3
  • I think you meant char array[], not int array[]. Commented Feb 18, 2014 at 19:08
  • @barakmanos Why? Ints can store hex values too. Commented Feb 18, 2014 at 19:09
  • Oh, sorry, didn't see the "equivalent" there... Commented Feb 18, 2014 at 19:09

2 Answers 2

4

An int is implicitly convertible to char, you don't need any casts. All standard containers have constructors that take a pair of iterators, so you can pass the beginning and the end of the array:

std::string so( std::begin(array), std::end(array) );

This might not be any faster than a manual loop, but I think it fits the criteria of neater and cleaner.

There's a clean way to do the same with array of pointers, too. Use Boost Indirect Iterator:

#include <boost/iterator/indirect_iterator.hpp>

std::string s (
    boost::make_indirect_iterator(std::begin(array)),
    boost::make_indirect_iterator(std::end(array)) );

One more thing I just noticed - you don't need a 0 in the int array just to mark the end of a string. std::end will deduce the size of the array and 0 will actualy end up in the resulting string.

Sign up to request clarification or add additional context in comments.

1 Comment

@Gizmo std::string so(array,array+length) should work - the end iterator is 1 past usable data, in this case array+length should point to 0x00 value in array;
0

If you're looking for a (slightly) faster way, then you can do:

char str[sizeof(array)/sizeof(*array)];

for (int i=0; i<sizeof(array)/sizeof(*array); i++)
    str[i] = (char)array[i];

std::string so(str);

This will "save you" the repeated call to std::string::operator+=...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.