user200081
user200081

Reputation: 563

Shift a string by least significant bit first?

I have a string of 0's and 1's that I'd like to shift the bits of. For example, if my string had the following:

00000011

I'd like to turn it into

11000000

I have the idea on how to do it from an unsigned char, but I'm not entirely sure if you can use the bit shift operation on strings. Might anyone know how to do so with strings? Here's the code for unsigned chars.

unsigned char shift(unsigned char *bits)
{
  unsigned char sum = 0;
  for(int i = 7; i >= 0; i--)
  {
    sum += bits[i];
    sum <<= 1;
  }
  return sum;
}

If anyone could help, that'd be great! Thanks!

Upvotes: 1

Views: 1286

Answers (1)

NPE
NPE

Reputation: 500287

No, you can't use bit shift operators on strings.

If I understood your code correctly, you're simply reversing the order of the bits. If the input is a string, you just need to reverse the string.

For C and C++ recipes, see How do you reverse a string in place in C or C++?

Upvotes: 1

Related Questions