假设一个M大小的位序列和另一个N大小的位序列,M>>N。M和N都可以保存在整数数组中:如果N的长度为30,则只需要一个整数数组,但如果N的长度为300,则需要一个10个整数数组来存储它。
我要做的是在m中移动n,并为m中的每个可能位置k找到n和m(k)之间的差异数(通过异或运算)。如果m有10000位,n有100位,则有10000-100=9900个位置将执行异或比较。
你知不知道有一个库可以做到这一点,或者提出一个算法?我知道这可以用很多其他的方法来完成,但是我相信最快的方法就是这里提出的方法如果你能想出一个更快的方法,那么我愿意接受建议!
我更喜欢C或C++的东西,但其他语言,甚至伪代码也是可以接受的。
提前谢谢。

最佳答案

这是一个完整而有效的解决方案。作为练习留给读者:)

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

#define M_SIZE 100
#define N_SIZE 25
#define bitsToBytes(n) ((n + 7)/8)

typedef unsigned char byte;

void dumpBytes(byte *arr, size_t size) {
   int b;
   for (b=0; b<size; b++) {
      printf("%02x", *arr++);
   }
   printf("\n");
}

int main(int argc, char *argv[]) {

   byte M[bitsToBytes(M_SIZE)], N[bitsToBytes(N_SIZE)];

   /* Fill M and N with random bits */

   int b;

   for (b=0; b<sizeof(M); b++) {
      M[b] = 0xff & rand();
   }
   for (b=0; b<sizeof(N); b++) {
      N[b] = 0xff & rand();
   }

   /* Create a couple of arrays big enough for M_SIZE + N_SIZE,
      to allow shifting N all the way before the left of M. */
   #define MN_SIZE (M_SIZE + N_SIZE)
   #define MN_BYTES (bitsToBytes(MN_SIZE))
   byte MM[MN_BYTES], NN[MN_BYTES];

   /* Zero out MM, NN, then copy M, N there (right justified). */
   int offset = sizeof(MM) - sizeof(M);
   memset (MM, 0, sizeof(MM)); memcpy(MM+offset, M, sizeof(M));
   offset = sizeof(NN) - sizeof(N);
   memset (NN, 0, sizeof(NN)); memcpy(NN+offset, N, sizeof(N));

   dumpBytes(MM, MN_BYTES);
   /* Count up "difference bits" until NN has been left-shifted into oblivion. */
   int s;
   for (s=0; s<MN_SIZE; s++) {
      int sum = 0;
      for (b=0; b<MN_BYTES; b++) {
  int xor = MM[b] ^ NN[b];
  while (xor != 0) {
     sum += (xor & 1);
     xor >>= 1;
  }
      }
      dumpBytes(NN, MN_BYTES);
      printf("Shift: %4d; bits: %3d.\n", s, sum);
      /* shift NN one bit to the left */
      for (b=0; b<MN_BYTES; b++) {
  NN[b] <<= 1;
  if (b < (MN_BYTES - 1) && ((NN[b+1] & 0x80) != 0)) NN[b] |= 1;
      }
   }
}

关于c - 整数数组的按位异或运算,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1680615/

10-09 02:56