Difference between revisions of "ASC"

From QB64 Wiki
Jump to navigation Jump to search
Line 1: Line 1:
ASC returns the [[ASCII]] code number of a certain [[STRING]] text character or a keyboard press.
The '''ASC''' function returns the [[ASCII]] code number of a certain [[STRING]] text character or a keyboard press.

Revision as of 19:07, 22 September 2009

The ASC function returns the ASCII code number of a certain STRING text character or a keyboard press.

Syntax: code% = ASC(character$)

  • String parameter must be a string with a length of at least 1 byte.
  • If the string used with ASC has more than one character, the first byte character code is returned.
  • Code INTEGER values returned will range from 0 to 255 only.
  • ASC will create an error if reading an empty string ("") returned in an INKEY$ loop when there is no keypress!
  • ASC returns 0 when reading 2 byte codes returned by INKEY$ when the arrow, funtion, central keys or certain combination keyboard presses are used.

Example 1:

PRINT ASC("Be a rockstar")



Explanation: The ASCII code for "A" is 65 and the ASCII code for "B" is 66.

Note: The ASCII code for "A" and "a" are different by the value of 32, "A" + 32 is "a", 65("A") + 32 = 97("a").

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

DO: SLEEP ' requires a keypress to run loop once
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
LOCATE 10, 10: PRINT entry$; ' display present entry to user(semicolon required)
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: CHR$ (function), VAL, STRING$, ASCII


Go to Keyword Reference - Alphabetical

Go to Keyword Reference - By usage