Stages 71-74
Posted: Fri Dec 10, 2021 10:21 pm
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!
- 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/sys.sbi";
decl func hex2dec(s: str): uint;
dim h: str = "7FFFFFFF"; ' 2147483647
dim d: uint;
main do
d = hex2dec(h);
print(d);
end;
func hex2dec(s: str): uint
dim p: ptr;
dim r: uint = 0;
dim b: uint8;
do
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
break;
end;
r = r * 16 + b;
p = p + 1;
end;
hex2dec = r;
end;