; val,ok:=hex('hex number')

; will read a string containing text representing a hexadecimal value,
; which can start with '$' or '0x' if it wants.
; terminates reading the string on end of line or space ("\0", "\n" or " ")
; or after reading 8 digits, or on an invalid character.
; val is the 32bit value of the hex number, ok is zero if invalid
; characters were encountered, non-zero otherwise.

; 'ok' is true if there was no error reading, otherwise false

	xdef	hex_i
hex_i	movem.l	d2-d3/a0-a1,-(sp)	; 4*4=16 onto stack
	move.l	[4+16](sp),a0

	cmp.b	#'$',(a0)
	bne.s	.noadd
	addq.l	#1,a0
.noadd	cmp.b	#'0',(a0)
	bne.s	.noadd2
	cmp.b	#'x',1(a0)
	bne.s	.noadd2
	addq.l	#2,a0
.noadd2
	moveq	#0,d0
	moveq	#0,d1
	moveq	#0,d2

	moveq	#8,d3
.nxtlet	lea	hextable(pc),a1

.nxtcmp	move.b	(a1),d2
	beq.s	.nothex
	addq.l	#2,a1
	cmp.b	(a0),d2
	bne.s	.nxtcmp

	move.b	-1(a1),d1	; d1=hex digit value
	asl.l	#4,d0
	add.b	d1,d0

	subq	#1,d3		; exit on 8 digits
	beq.s	.done

	addq.l	#1,a0
	cmp.b	#" ",(a0)
	beq.s	.done		; exit on " "
	cmp.b	#10,(a0)
	beq.s	.done		; exit on "\n"
	tst.b	(a0)
	bne.s	.nxtlet		; exit on "\0"

.done	moveq	#-1,d1
	bra.s	.exit	; OK

.nothex	moveq	#0,d0
	moveq	#0,d1	; FAIL
.exit	movem.l	(sp)+,d2-d3/a0-a1
	rts

hextable
	dc.b	'0', 0
	dc.b	'1', 1
	dc.b	'2', 2
	dc.b	'3', 3
	dc.b	'4', 4
	dc.b	'5', 5
	dc.b	'6', 6
	dc.b	'7', 7
	dc.b	'8', 8
	dc.b	'9', 9
	dc.b	'a', 10
	dc.b	'b', 11
	dc.b	'c', 12
	dc.b	'd', 13
	dc.b	'e', 14
	dc.b	'f', 15
	dc.b	'A', 10
	dc.b	'B', 11
	dc.b	'C', 12
	dc.b	'D', 13
	dc.b	'E', 14
	dc.b	'F', 15
	dc.b	0,   0
