Page 1 of 1

bit shifts of constants

Posted: 01 October 2011, 13:36 PM
by stevech
does ZB have a compile-time operator, for constants, for left/right shift?

like
(1<<constant1) OR (1<<constant2)

versus
shl(1, constant1) OR shl(1, constant2)

shl() is run-time, I suppose, unless the compiler's optimizer converts the above to a compile-time constant rather than using run time function calls despite the constants

Re: bit shifts of constants

Posted: 01 October 2011, 14:13 PM
by dkinzer
stevech wrote:does ZB have a compile-time operator, for constants, for left/right shift?
For many functions, including Shl and Shr, if the parameters are constant the compiler computes the result at compile-time. This can be seen, for example, by compiling this code:

Code: Select all

Dim b as Byte
Sub Main&#40;&#41;
    b = Shl&#40;1, 5&#41;
End Sub
which results in this intermediate C code (for native mode devices):

Code: Select all

static uint8_t mzv_b;
void zf_Main&#40;void&#41;
&#123;
	mzv_b = 32;
&#125;
or this VM code:

Code: Select all

            Sub Main&#40;&#41;
            	b = Shl&#40;1, 5&#41;
0019 1a20        PSHI_B         0x20 &#40;32&#41;
001b 204001      POPA_B         0x0140 &#40;320&#41;
            End Sub
001e 06          RET

Posted: 01 October 2011, 14:15 PM
by dkinzer
I should have remarked that the same compile-time computation applies to expressions with constant operands, too, so your example of shl(1, constant1) OR shl(1, constant2) will evaluate to a constant at compile-time.

Posted: 01 October 2011, 14:19 PM
by stevech
Thanks. I assume that applies as well where the storage is an I/O register

DDRB
or SPI register, etc.

Posted: 01 October 2011, 16:58 PM
by dkinzer
stevech wrote:I assume that applies as well where the storage is an I/O register.
Yes. The use to which an expression's value is put is immaterial - the compiler will optimize an expression as much as it can, possibly reducing it to a constant value.