Types Conversions

Conversion of variable of one type to a variable of another type is typecasting. mikroBasic PRO for ARM supports both implicit and explicit conversions for built-in types.

Implicit Conversion

Compiler will provide an automatic implicit conversion in the following situations:

Promotion

When operands are of different types, implicit conversion promotes the less complex type to more complex type taking the following steps:

bit       →  byte/char
byte/char →  word
short     →  integer
short     →  longint
integer   →  longint
integral  →  float

Higher bytes of extended unsigned operand are filled with zeroes. Higher bytes of extended signed operand are filled with bit sign (if number is negative, fill higher bytes with one, otherwise with zeroes). For example:

dim a as byte
dim b as word
'...
a = $FF
b = a  ' a is promoted to word, b becomes $00FF

Clipping

In assignments and statements that require an expression of particular type, destination will store the correct value only if it can properly represent the result of expression, i.e. if the result fits in destination range.

If expression evaluates to a more complex type than expected, excess of data will be simply clipped (higher bytes are lost).

dim i as byte
dim j as word
'...
j = $FF0F
i = j  ' i becomes $0F, higher byte $FF is lost

Explicit Conversion

Explicit conversion can be executed at any point by inserting type keyword (byte, word, short, integer, longint, or float) ahead of the expression to be converted. The expression must be enclosed in parentheses. Explicit conversion can be performed only on the operand left of the assignment operator.

Special case is the conversion between signed and unsigned types. Explicit conversion between signed and unsigned data does not change binary representation of data — it merely allows copying of source to destination.

For example:

dim a as byte
dim b as short
'...
b = -1
a = byte(b)  ' a is 255, not 1

' This is because binary representation remains
' 11111111; it's just interpreted differently now

You can’t execute explicit conversion on the operand left of the assignment operator:

word(b) = a   ' Compiler will report an error

Conversions Examples

Here is an example of conversion:

program test

typedef TBytePtr as ^byte

dim arr as word[10]
    ptr as TBytePtr

dim a, b, cc as byte
dim dd as word

main:
  a = 241
  b = 128

  cc  = a + b         ' equals 113
  cc  = word(a + b)   ' equals 113
  dd  = a + b         ' equals 369

  ptr = TBytePtr(@arr)
  ptr = ^byte(@arr)
end.
Copyright (c) 2002-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code