0

First of all i have an array like this :

unsigned char testArray[4]={0x00,0x10,0x20,0x00};

It should be the input of the following method:

void ReadArray(unsigned char * input)
{
   std::string str( input, input + sizeof input / sizeof input[0]);
   std::cout << str << std::endl;
}

I am looking for a way to get a string like: 00102000 according to this example.

Using

for (int i =0; i < str.size(); i++)
{
    cout << str[i];
}

i am not even able to display those values.

enter image description here

I am usually a C# guy and i am a bit lost here. A hint would be nice.

Update

This is a working version:

void Read(unsigned char * input)
{
   std::string str( input, input + sizeof input / sizeof input[0] );

   std::stringstream ss;

   for (int i =0; i < str.size(); i++)
   {
       ss  << std::hex << (int)str[i];
       std::string mystr = ss.str();

       if (mystr.size() == 1)
       mystr = "0" + mystr;

       cout <<mystr;
       ss.str("");
   }
}

Result

enter image description here

Olaru Mircea
  • 2,570
  • 26
  • 49

1 Answers1

3

sizeof input / sizeof input[0] is not going to give you the size of the array. Once you pass an array as a pointer to a function you lose all ability to get the array size from the pointer.

To fix this you either need to pass the size of the array into the function or you can pass beginning and end pointers. You could also use a template which will get the size for you like:

template<typename T, size_t SIZE>
void ReadArray(T (&input)[SIZE]) {
    std::string str( input, input + SIZE);
    std::cout << str << std::endl;
}

Live Example

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • This is correct, you should either pass the size, begin/end pointers or use templates instead. – yizzlez Jul 22 '15 at 14:43
  • I was able to populate that string as you see in the image, or am i wrong? – Olaru Mircea Jul 22 '15 at 14:55
  • As a matter of fact, my code works perfect with "test" char array. but with hex values i get stuck. – Olaru Mircea Jul 22 '15 at 15:00
  • @OlaruMircea The code happens to work in your case as `sizeof input / sizeof input[0]` should give you 8 on a 64 bit machine or `4` on a 32 bit machine which is enough for you. if you have something bigger than that then it fails: http://coliru.stacked-crooked.com/a/8ce47996d9355ca1 – NathanOliver Jul 22 '15 at 15:03
  • @NathanOliver Thank you, I will take care of this detail, but as in this moment it works fine, i am struggling to transform that into 00102000. Do you have any hint about this ? – Olaru Mircea Jul 22 '15 at 15:08
  • cout << std::hex << (int)str[i]; this did the job. Thanks for your support. I will take care about that size. – Olaru Mircea Jul 22 '15 at 15:15
  • @OlaruMircea No problem. Glad you got it. – NathanOliver Jul 22 '15 at 15:16