This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

How can map some bit in a array

Dear all,

I want to access some continus bit,let me can modify the value,such as,
for(i = 0 ; i < 10 ; i++)
{
bit[i] = ?;
}

but you know,the bit var cann't build as a array in keil c51,but build some boolean var with byte will speed down the MCU and more code,Who can give me a good advice and a way,Thanks in advance.

Parents
  • Hi,

    I think you could do something like this:-

    #define noOfBits 10   /*required 'no of bits' in bit array */
    
    char bitNumber = 3;   /*  bit to access/test */
    char bArray[(noOfBits + 7)/8];  /* allocate enough space to store all bits */
    
    bArray[bitNumber/8] |= 1 << (bitNumber % 8); /* set bit */
    bArray[bitNumber/8] &= ~(1 << (bitNumber % 8)) /* reset bit */
    if (bArray[bitNumber/8] & (1 << (bitNumber % 8)) /* test bit none zero */
    
    

    The above does not allow you to (easily) declare your bits that you want to be stored in the bit array as 'bit bitName;'.
    It may be possible to write it more elegantly but hopefully this will give you some ideas on how to access bits, also you can 'enum' the bitNumbers to help clarify the bit positions in the array.

    Hope this helps,
    Mark.

Reply
  • Hi,

    I think you could do something like this:-

    #define noOfBits 10   /*required 'no of bits' in bit array */
    
    char bitNumber = 3;   /*  bit to access/test */
    char bArray[(noOfBits + 7)/8];  /* allocate enough space to store all bits */
    
    bArray[bitNumber/8] |= 1 << (bitNumber % 8); /* set bit */
    bArray[bitNumber/8] &= ~(1 << (bitNumber % 8)) /* reset bit */
    if (bArray[bitNumber/8] & (1 << (bitNumber % 8)) /* test bit none zero */
    
    

    The above does not allow you to (easily) declare your bits that you want to be stored in the bit array as 'bit bitName;'.
    It may be possible to write it more elegantly but hopefully this will give you some ideas on how to access bits, also you can 'enum' the bitNumbers to help clarify the bit positions in the array.

    Hope this helps,
    Mark.

Children
No data