Вопрос

I am required to write a function called bitstring, which takes a unsigned char that was created in this function:

size_t bs2n(string s)
{
  assert (s.size() > 0);
  if (s.size() == 1) 
    return s[0]-'0';
  else {
    string smaller = s.substr(0,s.size()-1); 
    return 2 * bs2n(smaller) + s[s.size()-1] - '0';
  }
}

This function takes 8 bits and returns a unsigned char between 0-255

I need to be able to convert it back, but I encountered a problem when writing down the function parameters and first line from class.

What I have is:

string unsignedchar bitstring(unsigned char)

I think for one that it should be:

string unsigned char bitstring(unsigned char val)

which would make a heck of a lot more sense, but still doesn't make sense why I need the first unsigned char...

How should I write the first line of the function?

Это было полезно?

Решение

The parameters aren't your problem, it would be your function declaration. You declare two return types to the function

string unsigned char bitstring(unsigned char val)

The function returns a string...wait no... an unsigned char... you need to define just one return type, e.g. leave out string. what you want to accomplish would be an array of unsigned chars, thus requiring the char to return a pointer to chars.

void bitstring(unsigned char val, unsigned char* array) //write to array
  • Note though that returning arrays is a bad practice and generally fails, if you allocate the array in the function and return a reference to it the reference will fail because the array will deconstruct at the end of a function. A better solution would be to pass an array that you want to read into as a parameter to the function, then write to THAT array.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top