我制作了这段代码来删除第一位,然后从下一个元素中追加位。这里的问题是,在第 8 个元素处,由于发生了所有移位,它全为零。这段代码很难看,但我认为它有效。我只是想知道是否有人可以提出更好的方法,以及如何删除每八个元素出现的零元素。
先感谢您。
注意* 只编码了 6 周:P
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
unsigned char copy;
int i, j, n;
int shiftright;
int shiftleft;
shiftright = 6;
shiftleft = 2;
int counter = 0;
printf("Enter a number of values to test: ");
scanf("%d", &n);
unsigned char* array = malloc(n * sizeof(unsigned char));
copy = 0b01111111;
printf("Initial Array:\n");
for (i = 0; i < n; i++)
{
array[i] = copy;
printf("%x ", array[i]);
}
printf("\n");
// magic starts happening here
i = 0;
array[i] <<= 1;
for (j = 0; j < n; j++)
{
// counter to check for the 8th element
if (counter == 7)
{
counter = 0;
j++;
array[j] <<= 1;
}
counter++;
printf("sweep: %d\n", j);
// bitwise operations to remove zeros and append bits together
for (i = j; i < j + 1; i++)
{
if (array[i] == 0)
{
i++;
j++;
}
copy = array[i + 1];
copy >>= shiftright;
array[i] |= copy;
array[i + 1] <<= shiftleft;
shiftright--;
shiftleft++;
if (shiftright == -1)
{
shiftright = 6;
}
if (shiftleft == 9)
{
shiftleft = 2;
}
for (i = 0; i < n; i++)
{
printf("%x ", array[i]);
}
}
printf("\n");
}
return 0;
}