Messy code removes the 1st bit appends from the next element
I made this code to remove the first bit and then append bits from the
next element. Problem here is that at the 8th element its all zeros
because of all the shifts that occur. This code is ugly as fuck but I
think it works. I was just wondering if anyone could suggest a better way
of doing this, and how would i remove that zero element that occurs every
eight elements.
Thank you in advance.
note* only been coding for 6 weeks :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;
}
No comments:
Post a Comment