Caché ObjectScript Reference
$BITFIND


Returns the position of the specified bit value within a bitstring.
Synopsis
$BITFIND(bitstring,bitvalue,position,direction)
If the desired bit value is not found, or if
position (searching forward) is greater than the number of bits within the bitstring, the return value is 0. If the specified
bitstring is an undefined variable, the return value is 0. If the specified
bitstring is not a valid bitstring, an <INVALID BIT STRING> error is issued.
// Set a to [0,0,1,1,0]
SET $BIT(a,1) = 0
SET $BIT(a,2) = 0
SET $BIT(a,3) = 1
SET $BIT(a,4) = 1
SET $BIT(a,5) = 0
// Find first 1 bit within a
WRITE !,$BITFIND(a,1)
If
bitstring = [0,0,1,1,0], when searching from
position 3, the first bit of value 1 is bit position 3 (because search is inclusive of the
position bit) and the first bit of value 0 is bit position 5:
// Set a to [0,0,1,1,0]
SET $BIT(a,1) = 0
SET $BIT(a,2) = 0
SET $BIT(a,3) = 1
SET $BIT(a,4) = 1
SET $BIT(a,5) = 0
// Find first 1 bit from position 3
WRITE !,"found a 1 at bit position:",$BITFIND(a,1,3)
// Find first 0 bit from position 3
WRITE !,"found a 0 at bit position:",$BITFIND(a,0,3)
If
bitstring = [0,0,1,1,0], when searching backwards from
position 99, the first bit of value 1 is bit position 4 and the first bit of value 0 is bit position 5:
// Set a to [0,0,1,1,0]
SET $BIT(a,1) = 0
SET $BIT(a,2) = 0
SET $BIT(a,3) = 1
SET $BIT(a,4) = 1
SET $BIT(a,5) = 0
WRITE !,"found a 1 at bit position:",$BITFIND(a,1,99,1)
WRITE !,"found a 0 at bit position:",$BITFIND(a,0,99,1)
The following example returns a list of all of the 1 bit positions and a list of all of the 0 bit positions:
// Set a to [0,0,1,1,0]
SET $BIT(a,1) = 0
SET $BIT(a,2) = 0
SET $BIT(a,3) = 1
SET $BIT(a,4) = 1
SET $BIT(a,5) = 0
SET pos=0
WRITE !,"Bit positions with value 1: "
FOR { SET pos=$BITFIND(a,1,pos+1) QUIT:'pos WRITE pos,", " }
WRITE !,"Bit positions with value 0: "
FOR { SET pos=$BITFIND(a,0,pos+1) QUIT:'pos WRITE pos,", " }
The following example returns the position of the first 1 bit in a random 16bit bitstring generated by
$FACTOR:
SET x=$RANDOM(65536)
FOR i=1:1:16 {WRITE $BIT($FACTOR(x),i) }
WRITE !,"The first 1 bit is at position ",$BITFIND($FACTOR(x),1)