Omnimaga

Calculator Community => TI Calculators => ASM => Topic started by: ralphdspam on July 07, 2011, 10:55:05 pm

Title: Checking the amount of set bits.
Post by: ralphdspam on July 07, 2011, 10:55:05 pm
Hi, is there an efficient way to check if a byte has only one reset bit?

Example:
%11111011
True, because bit 2 is reset.

%01110111
False, because bit 3 and 7 are reset. 

Thanks for all of the suggestions.  :)
Title: Re: Checking the amount of set bits.
Post by: Iambian on July 07, 2011, 11:01:35 pm
Code: [Select]
;Input: A=byteToCheck
;Destroys B.
CheckOneBitUnset:
 cpl
 ld b,8
 rlca
 jr c,$+6
 djnz $-3
 scf
 ret  ;returns with a carry if no bits are set
 and %11111110
 ret  ;zero if only one bit is unset, nonzero if others are set. No carry regardless.
Check to see if that actually works. Just made it up on the spot.
Title: Re: Checking the amount of set bits.
Post by: calc84maniac on July 07, 2011, 11:04:06 pm
This method tests for zero or one reset bits (you'd have to check the $FF case manually)
Code: [Select]
;Outputs Z if 0-1 bits of A are reset
ld b,a
inc a
or b
inc a
Title: Re: Checking the amount of set bits.
Post by: ralphdspam on July 07, 2011, 11:07:58 pm
This method tests for zero or one reset bits (you'd have to check the $FF case manually)
Code: [Select]
;Outputs Z if 0-1 bits of A are reset
ld b,a
inc a
or b
inc a
Thanks!  That is awesomeness!  A winner is you!  :D
Title: Re: Checking the amount of set bits.
Post by: Quigibo on July 07, 2011, 11:41:03 pm
This is the smallest I could come up with:
Code: [Select]
;Input: a = byte to check
;Flags: z = Exactly 1 reset bit
cpl
ld b,a
dec a
xor b
add a,1
rra
xor b

Edit: Nevermind, calc wins!  Although you do have to special case with his, but even with that I think it would still be smaller by one byte.
Title: Re: Checking the amount of set bits.
Post by: calc84maniac on July 07, 2011, 11:45:27 pm
Hmm, I just realized a fairly simple way to handle the special case:
Code: [Select]
;Outputs Z if exactly 1 bit of A is reset
  ld b,a
  inc a
  jr z,special
  or b
special:
  inc a