Skip to main content

Bitstrings

A bitstring is another special kind of string, made up of a compressed series of bits. A 32K variable can hold almost 256K bits. There are special functions for creating and working with bitstrings.

  • $Bit retrieves or sets (used with Set) a bit to 1 or 0. The examples below use $Random(2) to randomly generate either a 1 or a 0.

  • $BitCount counts bits.

  • $BitFind finds the next bit with a specific value (1 or 0).

  • $BitLogic performs bit-wise operations (and, or, not, xor) on bitstrings.

  • $Factor converts an integer to the bitstring representing it. For example, $Factor(20) returns the bitstring 00101 (only the bits whose place values are 4 and 16 are set).

Since the bitstring is compressed, you shouldn't Write it—either use $Bit, or you can use the ZWrite command, which shows both the byte and bit contents.

Terminal


USER>for i = 1:1:40 {set $bit(b, i) = $random(2)}

USER>write $bitcount(b, 0)
23
USER>write $bitcount(b, 1)
17
USER>for i = 1:1:40 {write $bit(b, i)}
0100110001000110101011001100010010000111
USER>write $bitfind(b, 1, 1) // find the first 1 bit, starting at position 1
2
USER>write $bitfind(b, 0, 1) // find the first 0 bit, starting at position 1
1
USER>write $bitfind(b, 1, 3) // find the next 1 bit, starting at position 3
5
USER>for i = 1:1:40 {set $bit(c, i) = $random(2)}

USER>set d = $bitlogic(b & c)

USER>for i = 1:1:40 {write $bit(b, i)}
0100110001000110101011001100010010000111
USER>for i = 1:1:40 {write $bit(c, i)}
0111001111001011110100100110101110111011
USER>for i = 1:1:40 {write $bit(d, i)}
0100000001000010100000000100000010000011
USER>set f = $factor(3456)

USER>zwrite f  // shows the bits representing 3456
f=$zwc(128,4)_$c(128,13,0,0)/*$bit(8,9,11,12)*/
USER>set sum = 0 write !, sum for i=8,9,11,12 { set sum = sum + (2 ** (i-1)) write " + 2**", (i-1) } write " = ", sum 

0 + 2**7 + 2**8 + 2**10 + 2**11 = 3456
USER>
Feedback