c -对字符数组进行按位操作



所以我有一个二进制表示的数字作为一个字符数组。我需要做的是将这个表示向右移动11位。

例如,

我有一个字符数组,目前存储这个字符串:11000000111001在执行逐位移位后,我将得到110,在它之前有一些零。

我试着使用这个函数,但它给了我奇怪的输出:

char *shift_right(unsigned char *ar, int size, int shift)
{
int carry = 0;                              // Clear the initial carry bit.
while (shift--) {                           // For each bit to shift ...
    for (int i = size - 1; i >= 0; --i) {   // For each element of the array   from high to low ...
        int next = (ar[i] & 1) ? 0x80 : 0;  // ... if the low bit is set, set the carry bit.
        ar[i] = carry | (ar[i] >> 1);       // Shift the element one bit left and addthe old carry.
        carry = next;                       // Remember the old carry for next time.
    }
}
return ar;
}

在这方面的任何帮助将非常感激;

它们只是字符…

char *shift_right(unsigned char *ar, int size, int shift)
   {
   memmove(&ar[shift], ar, size-shift);
   memset(ar, '0', shift);
   return(ar);
   };

或者,将字符串转换为long-long类型,将其移位,然后返回字符串:

char *shift_right(char *ar, int size, int shift)
   {
   unsigned long long x;
   char *cp;
   x=strtoull(ar, &cp, 2);  // As suggested by 'Don't You Worry Child'
   x = x >> shift;
   while(cp > ar)
      {
      --cp;
      *cp = (1 & x) ? '1' : '0';
      x = x >> 1;
      }
   return(ar);
   };

如果你真的想使用按位移位,那么你不能在字符串上这样做。根本不可能!!

你必须将其转换为整数(使用strtol),然后进行位移。之后,将其转换回字符串(没有标准库函数,使用for循环)。

我建议保持代码简单易读。

#include <stdio.h>
#include <stdlib.h>
void shift_right (char* dest, const char* source, int shift_n)
{
  uint16_t val = strtoul(source, NULL, 2);
  val >>= shift_n;
  for(uint8_t i=0; i<16; i++)
  {
    if(val & 0x8000) // first item of the string is the MSB
    {
      dest[i] = '1';
    }
    else
    {
      dest[i] = '0';
    }
    val <<= 1;    // keep evaluating the number from MSB and down
  }
  dest[16] = '';
}

int main()
{
  const char str [16+1] = "0011000000111001";
  char str_shifted [16+1];
  puts(str);
  shift_right(str_shifted, str, 11);
  puts(str_shifted);
  return 0;
}

最新更新