Addressing bits in variables

In integer variables individual bits can be accessed. For this, the index of the bit to be addressed is appended to the variable, separated by a dot. The bit-index can be given by any constant. Indexing is 0-based.

Note

Bitaccess in Direct variables ( The library SysLibDirect.lib) is not allowed.

Example

a : INT;

b : BOOL;

a.2 := b;

The third bit of the variable a will be set to the value of the variable b.

If the index is greater than the bit width of the variable, the following error message is issued: Index ‘<n>’ outside the valid range for variable ‘<var>’!

Bit addressing is possible with the following variable types: SINT, INT, DINT, USINT, UINT, UDINT, BYTE, WORD, DWORD.

If the variable type does not allow it, the following error message is issued: “Invalid data type ‘<type>’ for direct indexing”

A bit access must not be assigned to a VAR_IN_OUT variable!

Bitaccess via \ a global constant:

If you have declared a global constant, which defines the bit-index, you can use this constant for a bitaccess.

Note

The project option ‘Replace constants’ (category Build) must be activated.

See in the following examples for such a bitaccess on a variable resp. a structure variable:

Declaration in global variables list for \ both examples:

Variable enable defines which bit should be accessed:

VAR_GLOBAL CONSTANT

enable:int:=2;

END_VAR

Example 1, Bitaccess on an integer variable:

Declaration in POU:

VAR

xxx:int;

END_VAR

Bitaccess:

xxx.enable:=true;   -> the third bit in variable xxx will be set TRUE

Example 2, Bitaccess on an integer structure \ component:

Declaration of structure stru1:

TYPE stru1 :

STRUCT

bvar:BOOL;

rvar:REAL;

wvar:WORD;

{bitaccess enable 42 ‘Start drive’}

END_STRUCT

END_TYPE

Declaration in POU:

VAR

x:stru1;

END_VAR

Bitaccess:

x.enable:=true;

This will set TRUE the 42. bit in variable x. Since bvar has 8 bits and rvar has 32 bits, the bitaccess will be done on the second bit of variable wvar, which as a result will get value 4.

Note

If a variable, which does a bitaccess on a structure variable with the aid of a global constant, should be displayed correctly in the input assistant, at monitoring in the declaration window and in the intellisense function. please use pragma {bitaccess} ( Pragma instructions for Initialization, Monitoring, Creation of symbols, Bitaccess, Linking) which is shown in the example. Then in addition you get displayed the global constant beyond the respective structure variable during monitoring in the declaration window:

../_images/779ec632437575af0a33139006eab46b