find number of 1's in an array for error detection

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • marwanharb
    New Member
    • Mar 2015
    • 3

    find number of 1's in an array for error detection

    hello, I'm receiving a char array consist of 8 characters, what I want to do is find the number of set bits in that array and then send it(total number) as a character to the transmitter so he can check, data is transmitted using serial port(RS232), where processing of data is done by DE0 FPGA.I've tried to use TestBit but the compiler doesn't know this function(I added #include "bit-manipulation.h" but it doesn't recognize this either) If any one can help me at that would be great .


    -- the code of my project:

    filed = open( "/dev/uart_0", O_RDWR );
    if (filed < 0){
    printf("the port can't be opened \n");
    }
    else {

    while(1){
    while(1){
    read (filed, &arr[0],1);
    if (arr[0] == 0x1F)

    break;
    }
    for (i=1; i<7; i++) {

    read (filed, &arr[i],1);
    }
    IOWR_ALTERA_AVA LON_PIO_DATA(LO AD1_BASE, 1);
    IOWR_ALTERA_AVA LON_PIO_DATA(M_ BASE,((arr[1])+(arr[2]<<8)));
    IOWR_ALTERA_AVA LON_PIO_DATA(E_ BASE,(arr[3]));
    IOWR_ALTERA_AVA LON_PIO_DATA(G_ BASE,((arr[5])+(arr[6]<<8)));

    IOWR_ALTERA_AVA LON_PIO_DATA(LO AD1_BASE, 0);

    for(k=0;k<10000 ; k++){}

    y = IORD_ALTERA_AVA LON_PIO_DATA(R_ BASE);

    c=(unsigned char) y;

    write(filed, &c,1);

    }
    }
    }
    return 0;

    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    To find a set bit use bitwise operators. For example:

    11000101

    To see if the 3rd bit from the right is set you AND the character to a mask:

    11000101
    00000100

    In the result you have a 1 bit where both the character and the mask have a 1 bit. in this case the result is

    00000100

    So, if the result is the same as the mask, then the bit is set.

    Now in your case you start with a mask of 10000000 followed by 01000000 followed by 00100000 until you get to 00000001.

    You get the 1 bit to shift right using the bit shift operator >>:

    unsigned char mmask = 128; //128 is 10000000

    mask = mmask >> 1; //mask is now 010000000

    Write a loop that examines 1 unsigned char. Then surround it with an outer loop for the number of unsigned chars.

    Comment

    Working...