문제

HI all,

Is there anyway by which we can declare variable specifying bit fields on those which are not any members of structures or unions.If not,then is there anyway by which we can just declare a variable by specifying the number of bits it is permitted to use.

Thanks maddy

도움이 되었습니까?

해결책

A really simple and old technique is to just define a number of #define variables whose values correspond to bit locations and then use AND and OR operations to clear or set them as appropriate. e.g.

#define BIT_0 0x0001
#define BIT_1 0x0002
#define BIT_2 0x0004
#define BIT_3 0x0008
#define BIT_4 0x0010

You then use them to set bit locations in a standard variable e.g.

int someVariable = 0;

someVariable = someVariable | BIT_1; //set bit 1 to 1. someVariable = 2

someVariable = someVariable & ~BIT_1; // clear bit 1. someVariable = 0

Not efficient or clever but easy to read.

edit - added If you wish to restrict which bits are valid for use then setup a mask value to apply as follows:

#define VALID_BIT_MASK 0x0009 // thus only bits 3 and 0 are valid

As an example

someVariable = someVariable | BIT_0 | BIT_2 | BIT_4; // someVariable now has value 21

someVariable = someVariable & VALID_BIT_MASK; // remove invalid  bits, someVariable value is now 1

Obviously someVariable is going to be byte, unsigned int or unsigned long, but say that you want only 11 bits set of an unsigned int (16 bits).

#define VALID_BIT_MASK 0x07FF; // 011111111111 in binary.

someVariable = someVariable & VALID_BIT_MASK; //strips off unwanted bits.

다른 팁

No - unless it happens to be the same size as a built-in type (e.g. 8, 16, 32 or 64 bits) then you would need to embed it in a struct.

No, you should use the technique shown here

there is no benefit in declaring a variable with bits other than built-in type. because compiler will ultimately reserve space for it 8,16,32 or 64 bits.e.g if you declare variable unsigned x:5; then compiler will create 8 bits of space to store it. because CPU can't read memory which is not multiple of 8

In the ARM context, use of bitwise field operations are common when configuring the hardware components of the SOC using C. LPC_SC->FLASHCFG = (LPC_SC->FLASHCFG & ~0x0000F000) | FLASHCFG_Val; updates a 4 bit field in a configuration register with the value of FLASHCFG_Val. Or, while (!(LPC_SC->PLL1STAT & (1<<10)));// Wait for PLOCK1 to test a single bit in a status register where 1<<10 indicates the 10th bit position.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top