2

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?

Kurt E
  • 367
  • 1
  • 2
  • 9

1 Answers1

0

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.
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
  • If i have an array say: string temp = ["106", "128", "88"]; and I run it through the function you gave me: bitstring(temp[i],temp); through a for loop that runs 3 times to go through the entire array will it change my temp function to be something like temp=["01101010", ect..]? – Kurt E Dec 13 '12 at 06:03
  • if you need additional help shoot me an email and i'll assist you further. – Syntactic Fructose Dec 13 '12 at 06:50