Skip to main content
Previous sectionNext section

$BITCOUNT

Returns the number of bits in a bitstring.

Synopsis

$BITCOUNT(bitstring,bitvalue)

Parameters

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 property reference.
bitvalue Optional — The value (0 or 1) to count within the bitstring.

Description

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 a Caché encoded bitstring generates an <INVALID BIT STRING> error. For further information, refer to General Information on Bitstring Functions.

Examples

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
  WRITE !,$BITCOUNT(a)
Copy code to clipboard

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)
Copy code to clipboard

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)
Copy code to clipboard

See Also