Skip to main content

$BITCOUNT (ObjectScript)

Returns the number of bits in a bitstring.




Argument Description
bitstring An expression that evaluates to a bitstring. Can be a variable of any type, $FACTOR, a user-defined function, or an oref.prop, ..prop, or i%prop (instance variable) property reference.
bitvalue Optional — The value (0 or 1) to count within the bitstring.


The $BITCOUNT function counts the number of bits within a bitstring. A bitstring is an encoded string which is interpreted by the system as a series of bits. You can create a bitstring using $BIT or $BITLOGIC.

$BITCOUNT(bitstring) returns the number of bits in bitstring.

$BITCOUNT(bitstring, bitvalue) returns the number of bits of type bitvalue (0 or 1) in bitstring.

The maximum bitstring length is 262,104 bits (32763 x 8).

Specifying a bitstring value that is not an InterSystems IRIS encoded bitstring generates an <INVALID BIT STRING> error. For further information, refer to General Information on Bitstring Functions.


If bitstring= [0,0,1,1,0], then the result of $BITCOUNT(bitstring) is 5:

  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

If bitstring = [0,0,1,1,0], then the result of $BITCOUNT(bitstring,0) would be 3.

  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 !,"number of zero bits:",$BITCOUNT(a,0)
  WRITE !,"number of one bits: ",$BITCOUNT(a,1)

The following example returns the number of 1 bits in a random 16-bit bitstring generated by $FACTOR:

   SET x=$RANDOM(65536)
   FOR i=1:1:16 {WRITE $BIT($FACTOR(x),i) }
   WRITE !,"Number of 1 bits=",$BITCOUNT($FACTOR(x),1)

See Also

FeedbackOpens in a new tab