【发布时间】:2013-09-08 06:00:31
【问题描述】:
我编写了这段代码来删除第一位,然后从下一个元素中追加位。这里的问题是,在第 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;
}
【问题讨论】:
-
请不要发誓,这不是正确的地方
-
您可能想详细说明“第一位”的含义。它是最高位还是最低位。我很确定您的意思是前者(如果我认为是这样的话)。
-
WhozCraig 抱歉,是的,所以请注意副本是 0b01111111,所以我通过将它向左移动来摆脱那个 0,这样就留下了两个空闲空间来添加来自下一个元素的位等等等。
-
你应该可以运行这段代码来看看它是如何工作的。
-
作者不应该知道他的代码是怎么工作的吗?
标签: c logic bit-manipulation