	.286p

DIX_TEXT	SEGMENT	WORD PUBLIC 'CODE'
DIX_TEXT	ENDS

DIX_TEXT	SEGMENT
	ASSUME	CS:DIX_TEXT

; Given a 32 bit value in ax and dx, return the number of 1's.
; the return value will obviously be between 0 and 31.
; We use the fact that given that x is 4 bits long, the
; operation y = x - (x >> 1) - (x >> 2) - (x >> 3) will set
; y to the number of ones in x.  We can do 4 of these operations
; simultaneously on a 16 bit number and then add the results
; at the end.
	PUBLIC	@Ones
@Ones	PROC NEAR
	mov	cx,07777h
	mov	bx,ax
	shr	bx,1
	and	bx,cx
	sub	ax,bx	; 1st
	shr	bx,1
	and	bx,cx
	sub	ax,bx	; 2nd
	shr	bx,1
	and	bx,cx
	sub	ax,bx	; 3rd
; now add them together
	add	al,ah
	mov	ah,al
	shr	al,4
	and	ah,0fh
	add	al,ah
	sub	ah,ah

; repeat this for dx
	mov	bx,dx
	shr	bx,1
	and	bx,cx
	sub	dx,bx	; 1st
	shr	bx,1
	and	bx,cx
	sub	dx,bx	; 2nd
	shr	bx,1
	and	bx,cx
	sub	dx,bx	; 3rd
; now add them together
	add	dl,dh
	mov	dh,dl
	shr	dl,4
	and	dh,0fh
	add	dl,dh
	sub	dh,dh

	add	ax,dx
	ret	

@Ones	ENDP
DIX_TEXT	ENDS
	END
