BitClearString, BitFlipString, and BitSetString (String functions)

From m204wiki
Jump to navigation Jump to search

Set a bit in a string (String class)

[Introduced in Model 204 7.5]

These functions provide the ability to manipulate individual bits in a string via a bit number.


%result = string:BitClearString( bitNumber) Throws InvalidBitNumber

%result = string:BitFlipString( bitNumber) Throws InvalidBitNumber

%result = string:BitSetString( bitNumber) Throws InvalidBitNumber

Syntax terms

%resultA copy of the input (method object) string with a single bit (possibly) modified.
string The string for which a bit is to be modified.
bitNumber The bit number in the input string that is to be modified. Note that this is a bit number not a bit offset. So the first bit in the string is bit number 1.
  • BitClearString turns off the indicated bit. If it is already off, the bit stays off.
  • BitFlipString changes the indicated bit. If it is on, the bit is turned off; if it is off, the bit is turned on.
  • BitSetString turns on the indicated bit. If it is already on, the bit stays on.

Usage notes

  • Requesting a non-positive bit number, or a bit number past the the end of the string results in an InvalidBitNumber exception being thrown.
  • Since each byte in a string has 8 bits, the valid bit numbers range from 1 to the length of the string times 8. So a null (zero-length) string has no valid bits.
  • The value of a bit in a string can be tested with the BitValueString function.
  • Manipulating bits in a string provides an CPU and space efficient alternative to an array or [Arraylist Class|Arraylist]] when the possible values are always 0 or 1 or True or False. However, because the bit manipulation methods require the copying of the string value for each operation, this benefit tends to be blunted as the strings get longer. So while there is no restriction on the length of a string and bit number with the string that these methods will update – they can even update bit numbers greater than 2G since a 2G-1 longstring has 16G-8 bits
  • – it's probably not a good idea to use these functions heavily on strings longer than 255 bytes (2040 bits) or so.


This example creates a 128-byte string of null bytes, then sets every 3rd bit, clears every 4th bit, and then flips (inverts), every 5th bit, finally display the results in hexadecimal format:

%string is string len 255 %i is float ... %string = '00':x:left(128, pad='00':x') for %i from 1 to %string:length * 8 by 3 %string = %string:bitSetString(%i) end for for %i from 1 to %string:length * 8 by 4 %string = %string:bitClearString(%i) end for for %i from 1 to %string:length * 8 by 5 %string = %string:bitFlipString(%i) end for

See also