bit shifts of constants

Discussion about the ZBasic language including the System Library. If you're not sure where to post your message, do it here. However, do not make test posts here; that's the purpose of the Sandbox.
Post Reply
stevech
Posts: 715
Joined: 22 February 2006, 20:56 PM

bit shifts of constants

Post 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
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Re: bit shifts of constants

Post 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
- Don Kinzer
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Post 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.
- Don Kinzer
stevech
Posts: 715
Joined: 22 February 2006, 20:56 PM

Post by stevech »

Thanks. I assume that applies as well where the storage is an I/O register

DDRB
or SPI register, etc.
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Post 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.
- Don Kinzer
Post Reply