Campbell Scientific CR9000X Measurement and Control System User Manual

Page 288

Advertising
background image

Section 8. Processing and Math Instructions

Remarks

>> shifts the bit pattern to the right.

<< shifts the bit pattern to the left.

The Amount argument is the number of bits to shift left or right. Amount must
be an integer.

Bit shift operators (<< and >>) allow the program to manipulate the positions of
patterns of bits within an integer (CRBASIC Long type). Here are some
example expressions and the expected results:

&B00000001 << 1 produces &B00000010 (decimal 2)
&B00000010 << 1 produces &B00000100 (decimal 4)
&B11000011 << 1 produces &B10000110 (decimal 134)
&B00000011 << 2 produces &B00001100 (decimal 12)
&B00001100 >> 2 produces &B00000011 (decimal 3)

The result of these operators is the value of the left hand operand with all of its
bits moved by the specified number of positions. The resulting "holes" are
filled with zeroes.

Note that the Long data type is a signed integer. Shifting the bit pattern to the
right maintains the same sign (i.e., the most significant bit is maintained as a 1 if
the number is a negative).

An AND operation can be performed to strip unwanted bits for an unsigned
integer prior to performing the bit shift. Consider a sensor or protocol that
produces an integer value that is a composite of various "packed" fields. This
approach is quite common in order to conserve bandwidth and/or storage space.
Consider the following example of an eight byte value:

bits 7-6: value_1
bits 5-4: value_2
bits 3-0: value_3

Code to extract these values is shown in the following example.

Dim input_val as LONG
Dim value_1 as LONG
Dim value_2 as LONG
Dim value_3 as LONG

'read input_val somehow

value_1 = (input_val AND &B11000000)

>>

6

value_2 = (input_val AND &B00110000)

>>

4

'note that value_3 does not need to be shifted

value_3 = (input_val AND &B00001111)

With unsigned integers, shifting left is the equivalent of multiplying by two and
shifting right is the equivalent of dividing by two.

8-2

Advertising