KapaA
KapaA

Reputation: 307

C: converting Bit position to decimal

Scenario:

[Node A] < -------- Rf-interface ------> [Node B]

question:

Node A send a payload to Node B which is 6 bytes long. In this payload there is some information regarding available slots e.g. there are in total 6 bytes * 8 bits = 48 slots. Each slot can be either ON 1 or OFF 0.

For an example, then these slot numbers 0,2,5,7 are all ON. The bit representation of the payload will be: 10100101000000000 .... till the 48th bit.
These information are then send to Node B in the payload over the RF-interface.

At Node B, I need to convert the position of each bit representation in to decimal representation in an array (for some gui representation). back to the example:
I need to convert the payload with the bits: 10100101000000000... into active slots presentation in an array: e.g.

myArray[0] = 1;
myArray[1] = 0;
myArray[2] = 1;
myArray[3] = 0;
myArray[4] = 0;
myArray[5] = 1;
         .
         .
myArray[48] = x;

I am not good in bit mask, so any help wold be appreciated Thanks for all help!

Upvotes: 0

Views: 1315

Answers (3)

Will
Will

Reputation: 2131

for (int i = 0; i < buffer_size; i++) {
    for (int j = 7; j >= 0; j--) { // most significant bit first
        myArray[8 * i + j] = buffer[i] >> j & 1;
    }
}

Upvotes: 0

alpartis
alpartis

Reputation: 1122

Based on your example, I'm assuming the bitmap, the given 6-byte array is:

unsigned char bitmap[6] = {0xa5, 0x00, 0x00, 0x00, 0x00, 0x00};

And the results are destined for:

int myArray[48];

I would be inclined to loop through myArray from back to front and assign each value based on a test of the lowest order bit in the bitmap, then shift right for each loop iteration.

int bmi = 5;    // set bitmap index to end
int mai = 47;   // set myArray index to end
int i = 0;

while (mai >= 0) {
    for (i = 0; i < 8; i++) {
        myArray[mai] = bitmap[bmi] & 0x01;
        bitmap[bmi] >>= 1;
        --mai;
    }
    --bmi;
}
for (mai = 0; mai < 48; mai++) printf("%d", myArray[mai]);
printf("\n");

Upvotes: 0

How about this?:

    char *bitsToArray(char *data, int length)
    {
        char *rv = malloc(8*length);
        int i = 0;
        for(;i < length; ++i)
        {
            int j = 0;
            for(; j < 8; ++j)
            {
                rv[i*8+j] = (data[i]>>j)&1;
            }

        }
        return rv;
    }

It stores the least significant bit first. If you would like it to work in opposite bit order, you can change the line rv[i*8+j] = (data[i]>>j)&1; to rv[i*8+j] = (data[i]>>(7-j))&1;

Upvotes: 1

Related Questions