简体   繁体   中英

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!

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++?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM