finding the first bit set to '1'

Coding and general discussion relating to the compiler

Moderators: David Barker, Jerry Messina

Post Reply
Jerry Messina
Swordfish Developer
Posts: 1473
Joined: Fri Jan 30, 2009 6:27 pm
Location: US

finding the first bit set to '1'

Post by Jerry Messina » Fri Oct 06, 2023 1:56 pm

I ran across this code and thought it was a neat trick, so I adapted it to SF.
It locates the first bit in a byte that's set to a '1'

Code: Select all

//
// find lowest bit set in a byte
// returns bitmask indicating the first set bit, or 0 if none are set
//
function FindLowestBit(b as byte) as byte
  // this function computes 'result = b and -b'
  // however, the expression 'b and -b' will use 16-bit math by default
  // this assignment will allow the compiler to use bytes instead
  dim bb as byte = -b
  result = b and bb
end function
You can do the same with words...

Code: Select all

function FindLowestBit(w as word) as word
  // use words instead of longwords
  dim ww as word = -w
  result = w and ww
end function
And, if you want to find the first '0' bit instead just pass it the inverse

Code: Select all

y = FindLowestBit(not(x))

Post Reply