Shop OBEX P1 Docs P2 Docs Learn Events
P2 coding trick — Parallax Forums

P2 coding trick

Cluso99Cluso99 Posts: 18,069
edited 2018-04-28 00:10 in Propeller 2
I noticed this very smart coding trick Chip used in checking for a hex character (0..9, A..F, a..f).
I also found a shorter way to convert it to a binary nibble.
hexchrs		long	%00000000_00000000_00000000_00000000
		long	%00000011_11111111_00000000_00000000		'"0".."9"
		long	%00000000_00000000_00000000_01111110		'"A".."F"
		long	%00000000_00000000_00000000_01111110		'"a".."f"
		long	%00000000_00000000_00000000_00000000
		long	%00000000_00000000_00000000_00000000
		long	%00000000_00000000_00000000_00000000
		long	%00000000_00000000_00000000_00000000

.check		altb	x,#hexchrs		'check for hex
		testb	0,x		wc
	if_nc	ret				'if not hex, c=0

		testbn	x,#6		wz	'hex, "0".."9"?
	if_z	sub	x,#"0"			'if so, make $0..$9
	if_nz	bitl	x,#5			'else, force uppercase
	if_nz	sub	x,#"A"-10		'..make $A..$F
		ret				'c=1
Shorter conversion
.check		altb	x,#hexchrs		'check for hex
		testb	0,x		wc
	if_nc	ret				'if not hex, c=0

                testbn  x,#6            wz      'hex, "0".."9"?
        if_nz   add     x,#9                    '..make low nibble $A..$F
        _ret_   and     x,#$F                   'extract low nibble, return c=1
The add x,#9 converts "A..F" to "J..O" and "a..f" to "j..o". "J" is ascii $4A and "j" is ascii $6A.
Then we strip of the upper nibble from both the "0..9" and "J..O"/"j..o" leaving $00..$0F"

While it's shorter code to first check for ASCII $80 and above, rather than using the 8 long table we could use a 4 long table. This would save 2 longs.
But I believe Chip is looking for the quickest code.

Comments

Sign In or Register to comment.