From QB64 Wiki
Revision as of 20:57, 6 January 2010 by imported>Stylin (updated layout)
Jump to navigation Jump to search

The ASC function returns the _UNSIGNED _BYTE value of the first character of a STRING.


result% = ASC(expression$)


  • ASC returns the _UNSIGNED _BYTE value of the first character of expression$.
  • If expression$ is an empty string, an illegal function call is thrown.
  • CHR$ can be used to retrieve the character from a character value.


Outputs the character code of various strings:

PRINT ASC("A") PRINT ASC("Be a rockstar")

65 66

Example 2: Reading only numerical values input by a program user.

DO: SLEEP ' requires a keypress to run loop once K$ = INKEY$ code = ASC(K$) IF code >= 48 AND code <= 57 THEN entry$ = entry$ + CHR$(code) ' numbers only IF code = 46 AND flag = 0 THEN entry$ = entry$ + K$: flag = 1: mark = LEN(entry$) ' decimal point L = LEN(entry$) ' check entry length for possible backspace IF code = 8 AND L > 0 THEN ' backspace pressed and entry has a length entry$ = MID$(entry$, 1, L - 1) ' remove one character from entry$ IF L - 1 < mark THEN flag = 0 ' allow another decimal point if removed. LOCATE 10, POS(0) - 1: PRINT SPACE$(1); ' remove character from screen END IF LOCATE 10, 10: PRINT entry$; ' display present entry to user(semicolon required for correct POS return) LOOP UNTIL code = 13 AND L

Explanation: SLEEP waits for a keypress allowing background programs to use the processor time. It also keeps the press in the keyboard buffer for INKEY$ to read and guarantees that ASC will not read an empty string value to create an error. Filtered codes 48 to 57 are only number characters. One decimal point is allowed by using the flag. Code 8 is a backspace request which is ignored if the entry has no characters. If it is allowed it removes the last character from the entry and the screen. The loop exits when the user presses the [Enter] key and the entry has a length. Try to do that with INPUT!

See also

Keyword Reference - Alphabetical
Keyword Reference - By Usage
Main Wiki Page