Stages 71-74

Follow the development of the SharpBASIC compiler and share your thoughts and ideas.
Post Reply
User avatar
Site Admin
Posts: 51
Joined: Sun Nov 21, 2021 12:04 pm
Location: Netherlands

Stages 71-74

Post by frank »

Several functions have been added to the system library:

- left, mid, right for string manipulation (partially implemented in stage 70)
- instr (in-string) for searching a sub-string within a string, optionally with a start position
- cstr (convert to string) to convert any numeric value to string, including hexadecimal, binary and octal
- cdec (convert to decimal), which is the counterpart of cstr
- sadd (string address) to get the address of any string (constant, variable-length or fixed-length)
- len for the length/size of any datatype, including constants and immediate values

Example of hexadecimal to decimal conversion in SharpBASIC (the built-in function cdec is written in assembler, as are all functions). Note the use of sadd and the subsequent increment of the string pointer to go through each string character. This is much faster than using the mid function!

Code: Select all

' SharpBASIC hex to dec
' ---------------------
option strict;

incl "lib/";

decl func hex2dec(s: str): uint;

dim h: str = "7FFFFFFF";    ' 2147483647
dim d: uint;

main do
    d = hex2dec(h);

func hex2dec(s: str): uint
  dim p: ptr;
  dim r: uint = 0;
  dim b: uint8;
  p = sadd(s);
  loop do
    b = bya(p);
    when b
      is 97 to 102 do     ' a..f = 10-15
        b = b - 87;
      is 65 to 70 do      ' A..F = 10..15
        b = b - 55;
      is 48 to 57 do      ' 0..9
        b = b - 48;
      is other do
    r = r * 16 + b;
    p = p + 1;
  hex2dec = r;
Keep it simple!
Post Reply