; 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	.table(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

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