Vector(3)
๐ Vector(3) ๐
This is the Vector(3) page, straight outta User Contributed Perl Documentation. And yes bestie, it's the Bit::Vector one โ efficient bit vector, set of integers, and "big int" math library. No cap. We're doing the synopsis first, so grab a snack ๐.
๐ NAME ๐
Bit::Vector โ Efficient bit vector, set of integers and "big int" math library. (Yes, the "big int" is in quotes, keep the vibe ๐
.)
โจ SYNOPSIS โจ
okay so this is the whole call menu, and it's giving "I contain multitudes" ๐ . Every signature below is exactly what you type.
๐ฆ OVERLOADED OPERATORS ๐ฆ
๐ฆ MORE STRING IMPORT/EXPORT ๐ฆ
๐ CLASS METHODS ๐
Versionโ$version = Bit::Vector->Version();Word_Bitsโ$bits = Bit::Vector->Word_Bits(); # bits in a machine wordLong_Bitsโ$bits = Bit::Vector->Long_Bits(); # bits in an unsigned longnewโ constructor time, bestie:
$vector = Bit::Vector->new($bits); # bit vector constructor
@veclist = Bit::Vector->new($bits,$count);
new_Hexโ$vector = Bit::Vector->new_Hex($bits,$string);new_Binโ$vector = Bit::Vector->new_Bin($bits,$string);new_Decโ$vector = Bit::Vector->new_Dec($bits,$string);new_Enumโ$vector = Bit::Vector->new_Enum($bits,$string);Concat_Listโ$vector = Bit::Vector->Concat_List(@vectors);
๐ OBJECT METHODS ๐
newโ alternative call of constructor, iconic:
$vec2 = $vec1->new($bits); # alternative call of constructor
@veclist = $vec->new($bits,$count);
Shadowโ$vec2 = $vec1->Shadow(); # new vector, same size but emptyCloneโ$vec2 = $vec1->Clone(); # new vector, exact duplicateConcatโ$vector = $vec1->Concat($vec2);Concat_Listโ$vector = $vec1->Concat_List($vec2,$vec3,...);Sizeโ$bits = $vector->Size();Resizeโ resize era:
$vector->Resize($bits);
$vector->Resize($vector->Size()+5);
$vector->Resize($vector->Size()-5);
Copyโ$vec2->Copy($vec1);Emptyโ$vector->Empty();Fillโ$vector->Fill();Flipโ$vector->Flip();Primesโ$vector->Primes(); # Sieve of ErathostenesReverseโ$vec2->Reverse($vec1);Interval_Emptyโ$vector->Interval_Empty($min,$max);Interval_Fillโ$vector->Interval_Fill($min,$max);Interval_Flipโ$vector->Interval_Flip($min,$max);Interval_Reverseโ$vector->Interval_Reverse($min,$max);Interval_Scan_incโif (($min,$max) = $vector->Interval_Scan_inc($start))Interval_Scan_decโif (($min,$max) = $vector->Interval_Scan_dec($start))Interval_Copyโ$vec2->Interval_Copy($vec1,$offset2,$offset1,$length);Interval_Substituteโ$vec2->Interval_Substitute($vec1,$off2,$len2,$off1,$len1);is_emptyโif ($vector->is_empty())is_fullโif ($vector->is_full())equalโif ($vec1->equal($vec2))Lexicompare(unsigned) โ compare like:
if ($vec1->Lexicompare($vec2) == 0)
if ($vec1->Lexicompare($vec2) != 0)
if ($vec1->Lexicompare($vec2) < 0)
if ($vec1->Lexicompare($vec2) <= 0)
if ($vec1->Lexicompare($vec2) > 0)
if ($vec1->Lexicompare($vec2) >= 0)
Compare(signed) โ compare like:
if ($vec1->Compare($vec2) == 0)
if ($vec1->Compare($vec2) != 0)
if ($vec1->Compare($vec2) < 0)
if ($vec1->Compare($vec2) <= 0)
if ($vec1->Compare($vec2) > 0)
if ($vec1->Compare($vec2) >= 0)
to_Hexโ$string = $vector->to_Hex();from_Hexโ$vector->from_Hex($string);to_Binโ$string = $vector->to_Bin();from_Binโ$vector->from_Bin($string);to_Decโ$string = $vector->to_Dec();from_Decโ$vector->from_Dec($string);to_Enumโ$string = $vector->to_Enum(); # e.g. "2,3,5-7,11,13-19"from_Enumโ$vector->from_Enum($string);Bit_Offโ$vector->Bit_Off($index);Bit_Onโ$vector->Bit_On($index);bit_flipโ$bit = $vector->bit_flip($index);bit_test,containsโ both besties:
$bit = $vector->bit_test($index);
$bit = $vector->contains($index);
if ($vector->bit_test($index))
if ($vector->contains($index))
Bit_Copyโ$vector->Bit_Copy($index,$bit);LSB(least significant bit) โ$vector->LSB($bit);MSB(most significant bit) โ$vector->MSB($bit);lsb(least significant bit) โ$bit = $vector->lsb();msb(most significant bit) โ$bit = $vector->msb();rotate_leftโ$carry = $vector->rotate_left();rotate_rightโ$carry = $vector->rotate_right();shift_leftโ$carry = $vector->shift_left($carry);shift_rightโ$carry = $vector->shift_right($carry);Move_Leftโ$vector->Move_Left($bits); # shift left "$bits" positionsMove_Rightโ$vector->Move_Right($bits); # shift right "$bits" positionsInsertโ$vector->Insert($offset,$bits);Deleteโ$vector->Delete($offset,$bits);incrementโ$carry = $vector->increment();decrementโ$carry = $vector->decrement();incโ$overflow = $vec2->inc($vec1);decโ$overflow = $vec2->dec($vec1);addโ carry math, periodt:
$carry = $vec3->add($vec1,$vec2,$carry);
($carry,$overflow) = $vec3->add($vec1,$vec2,$carry);
subtractโ carry math again:
$carry = $vec3->subtract($vec1,$vec2,$carry);
($carry,$overflow) = $vec3->subtract($vec1,$vec2,$carry);
Neg,Negateโ both names, same energy:
$vec2->Neg($vec1);
$vec2->Negate($vec1);
Abs,Absoluteโ both names:
$vec2->Abs($vec1);
$vec2->Absolute($vec1);
Signโ sign check vibes:
if ($vector->Sign() == 0)
if ($vector->Sign() != 0)
if ($vector->Sign() < 0)
if ($vector->Sign() <= 0)
if ($vector->Sign() > 0)
if ($vector->Sign() >= 0)
Multiplyโ$vec3->Multiply($vec1,$vec2);Divideโ$quot->Divide($vec1,$vec2,$rest);GCD(Greatest Common Divisor) โ both forms:
$vecgcd->GCD($veca,$vecb);
$vecgcd->GCD($vecx,$vecy,$veca,$vecb);
Powerโ$vec3->Power($vec1,$vec2);Block_Storeโ$vector->Block_Store($buffer);Block_Readโ$buffer = $vector->Block_Read();Word_Sizeโ$size = $vector->Word_Size(); # number of words in "$vector"Word_Storeโ$vector->Word_Store($offset,$word);Word_Readโ$word = $vector->Word_Read($offset);Word_List_Storeโ$vector->Word_List_Store(@words);Word_List_Readโ@words = $vector->Word_List_Read();Word_Insertโ$vector->Word_Insert($offset,$count);Word_Deleteโ$vector->Word_Delete($offset,$count);Chunk_Storeโ$vector->Chunk_Store($chunksize,$offset,$chunk);Chunk_Readโ$chunk = $vector->Chunk_Read($chunksize,$offset);Chunk_List_Storeโ$vector->Chunk_List_Store($chunksize,@chunks);Chunk_List_Readโ@chunks = $vector->Chunk_List_Read($chunksize);Index_List_Removeโ$vector->Index_List_Remove(@indices);Index_List_Storeโ$vector->Index_List_Store(@indices);Index_List_Readโ@indices = $vector->Index_List_Read();Or,Unionโ set math slay:
$vec3->Or($vec1,$vec2);
$set3->Union($set1,$set2);
And,Intersectionโ set math slay:
$vec3->And($vec1,$vec2);
$set3->Intersection($set1,$set2);
AndNot,Differenceโ set math slay:
$vec3->AndNot($vec1,$vec2);
$set3->Difference($set1,$set2);
Xor,ExclusiveOrโ set math slay:
$vec3->Xor($vec1,$vec2);
$set3->ExclusiveOr($set1,$set2);
Not,Complementโ set math slay:
$vec2->Not($vec1);
$set2->Complement($set1);
subsetโif ($set1->subset($set2)) # true if $set1 is subset of $set2Normโ three norm besties:
$norm = $set->Norm();
$norm = $set->Norm2();
$norm = $set->Norm3();
Minโ$min = $set->Min();Maxโ$max = $set->Max();Multiplicationโ matrix moment:
$matrix3->Multiplication($rows3,$cols3,
$matrix1,$rows1,$cols1,
$matrix2,$rows2,$cols2);
Productโ another matrix moment:
$matrix3->Product($rows3,$cols3,
$matrix1,$rows1,$cols1,
$matrix2,$rows2,$cols2);
Closureโ$matrix->Closure($rows,$cols);Transposeโ$matrix2->Transpose($rows2,$cols2,$matrix1,$rows1,$cols1);
โจ IMPORTANT NOTES โจ
okay so this is the pre-game vibe check, bestie โ read it fr fr before you touch anything ๐
- Method naming conventions โ If a method name is completely in lower case, that means it returns a boolean value. (Except for the bit vector constructor method
new(), of course ๐.) - Boolean values โ Boolean values in this module are always a numeric zero (
0) forfalseand a numeric one (1) fortrue. No cap, itโs literally just numbers. - Negative numbers โ All numeric input parameters passed to any of the methods in this module are regarded as being UNSIGNED (as opposed to the contents of the bit vectors themselves, which are usually considered to be SIGNED). As a consequence, whenever you pass a negative number as an argument to some method of this module, it will be treated as a (usually very large) positive number due to its internal twoโs complement binary representation, usually resulting in an
"index out of range"error message and program abortion ๐ญ. (Yep, the program just gives up.) - Bit order โ Note that bit vectors are stored least order bit and least order word first internally. I.e., bit #0 of any given bit vector corresponds to bit #0 of word #0 in the array of machine words representing the bit vector. (Where word #0 comes first in memory, i.e., it is stored at the least memory address in the allocated block of memory holding the given bit vector.) Note however that machine words can be stored least order byte first or last, depending on your systemโs implementation. When you are exporting or importing a whole bit vector at once using the methods
Block_Read()andBlock_Store()(the only time in this module where this could make any difference), however, a conversion to and from"least order byte first"order is automatically supplied. In other words, whatBlock_Read()provides and whatBlock_Store()expects is always in"least order byte first"order, regardless of the order in which words are stored internally on your machine. This is to make sure that what you export on one machine usingBlock_Read()can always be read in correctly withBlock_Store()on a different machine. Note further that whenever bit vectors are converted to and from (binary or hexadecimal) strings, the RIGHTMOST bit is always the LEAST SIGNIFICANT one, and the LEFTMOST bit is always the MOST SIGNIFICANT bit. This is because in our western culture, numbers are always represented in this way (least significant to most significant digits go from right to left). Of course this requires an internal reversion of order, which the corresponding conversion methods perform automatically (without any additional overhead, itโs just a matter of starting the internal loop at the bottom or the top end) โจ. Word_related methods โ Note that all methods whose names begin withWord_are MACHINE-DEPENDENT! They depend on the size (number of bits) of anunsigned int(C type) on your machine. Therefore, you should only use these methods if you are ABSOLUTELY CERTAIN that portability of your code is not an issue! Note that you can use arbitrarily large chunks (i.e., fragments of bit vectors) of up to 32 bits IN A PORTABLE WAY using the methods whose names begin withChunk_. iykyk ๐- Chunk sizes โ Note that legal chunk sizes for all methods whose names begin with
Chunk_range from1toBit::Vector->Long_Bits();bits (0is NOT allowed!). In order to make your programs portable, however, you shouldnโt use chunk sizes larger than 32 bits, since this is the minimum size of anunsigned long(C type) on all systems, as prescribed by ANSI C. not you using a chunk size bigger than 32 bits and calling it portable ๐ - Matching sizes โ In general, for methods involving several bit vectors at the same time, all bit vector arguments must have identical sizes (number of bits), or a fatal
"size mismatch"error will occur. Exceptions from this rule are the methodsConcat(),Concat_List(),Copy(),Interval_Copy()andInterval_Substitute(), where no conditions at all are imposed on the size of their bit vector arguments. In methodMultiply(), all three bit vector arguments must in principle obey the rule of matching sizes, but the bit vector in which the result of the multiplication is to be stored may be larger than the two bit vector arguments containing the factors for the multiplication. In methodPower(), the bit vector for the result must be the same size or greater than the base of the exponentiation term. The exponent can be any size. - Index ranges โ All indices for any given bits must lie between
0and$vector->Size()-1, or a fatal"index out of range"error will occur. No exceptions, bestie. - Object persistence โ Since version
6.5,Bit::Vectorobjects can be serialized and de-serialized automatically withStorable, out-of-the-box, without requiring any further user action for this to work. This is also true for nested data structures (since version6.8). See theStorable(3) documentation for more details ๐ซถ.
๐ธ DESCRIPTION ๐ธ
๐ฆ OVERLOADED OPERATORS ๐ฆ
See Bit::Vector::Overload(3).
๐ MORE STRING IMPORT/EXPORT ๐
See Bit::Vector::String(3).
๐ CLASS METHODS ๐
$version = Bit::Vector->Version();โ Returns the current version number of this module. ๐ฉท$bits = Bit::Vector->Word_Bits();โ Returns the number of bits of anunsigned int(C type) on your machine. (Anunsigned intis also called a "machine word", hence the name of this method.) ๐ง$bits = Bit::Vector->Long_Bits();โ Returns the number of bits of anunsigned long(C type) on your machine. ๐$vector = Bit::Vector->new($bits);โ This is the bit vector constructor method. Call this method to create a new bit vector containing$bitsbits (with indices ranging from0to$bits-1). Note that โ in contrast to previous versions โ bit vectors of length zero (i.e., with$bits = 0) are permitted now. The method returns a reference to the newly created bit vector. A new bit vector is always initialized so that all bits are cleared (turned off). An exception will be raised if the method is unable to allocate the necessary memory. Note that if you specify a negative number for$bitsit will be interpreted as a large positive number due to its internal twoโs complement binary representation. In such a case, the bit vector constructor method will obediently attempt to create a bit vector of that size, probably resulting in an exception, as explained above ๐ญ.@veclist = Bit::Vector->new($bits,$count);โ You can also create more than one bit vector at a time if you specify the optional second parameter$count. The method returns a list of$countbit vectors which all have the same number of bits$bits(and which are all initialized, i.e., all bits are cleared). If$countis zero, an empty list is returned. If$bitsis zero, a list of null-sized bit vectors is returned. Note again that if you specify a negative number for$countit will be interpreted as a large positive number due to its internal twoโs complement binary representation. In such a case, the bit vector constructor method will obediently attempt to create that many bit vectors, probably resulting in an exception ("out of memory"). ๐ฅ$vector = Bit::Vector->new_Hex($bits,$string);โ This method is an alternative constructor which allows you to create a new bit vector object (with$bitsbits) and to initialize it all in one go. The method internally first calls the bit vector constructor methodnew()and then passes the given string to the methodfrom_Hex(). However, this method is more efficient than performing these two steps separately: First because in this method, the memory area occupied by the new bit vector is not initialized to zeros (which is pointless in this case), and second because it saves you from the associated overhead of one additional method invocation. An exception will be raised if the necessary memory cannot be allocated (see the description of the methodnew()immediately above for possible causes) or if the given string cannot be converted successfully (see the description of the methodfrom_Hex()further below for details). In the latter case, the memory occupied by the new bit vector is released first (i.e.,"free"d) before the exception is actually raised. ๐$vector = Bit::Vector->new_Bin($bits,$string);โ This method is an alternative constructor which allows you to create a new bit vector object (with$bitsbits) and to initialize it all in one go. The method internally first calls the bit vector constructor methodnew()and then passes the given string to the methodfrom_Bin(). However, this method is more efficient than performing these two steps separately: First because in this method, the memory area occupied by the new bit vector is not initialized to zeros (which is pointless in this case), and second because it saves you from the associated overhead of one additional method invocation. An exception will be raised if the necessary memory cannot be allocated (see the description of the methodnew()above for possible causes) or if the given string cannot be converted successfully (see the description of the methodfrom_Bin()further below for details). In the latter case, the memory occupied by the new bit vector is released first (i.e.,"free"d) before the exception is actually raised. ๐ฆ$vector = Bit::Vector->new_Dec($bits,$string);โ This method is an alternative constructor which allows you to create a new bit vector object (with$bitsbits) and to initialize it all in one go. The method internally first calls the bit vector constructor methodnew()and then passes the given string to the methodfrom_Dec(). However, this method is more efficient than performing these two steps separately: First because in this method,new()does not initialize the memory area occupied by the new bit vector with zeros (which is pointless in this case, becausefrom_Dec()will do it anyway), and second because it saves you from the associated overhead of one additional method invocation. An exception will be raised if the necessary memory cannot be allocated (see the description of the methodnew()above for possible causes) or if the given string cannot be converted successfully (see the description of the methodfrom_Dec()further below for details). In the latter case, the memory occupied by the new bit vector is released first (i.e.,"free"d) before the exception is actually raised. ๐$vector = Bit::Vector->new_Enum($bits,$string);
okay so this is the alt constructor that lets you make a brand-new bit vector object (with $bits bits in it, bestie) and fill it up all in one go, no cap. ๐ซถ
under the hood it first calls the bit vector constructor method new() and then hands your string over to from_Enum().
but here's the tea โ this method is more efficient than doing those two steps separately: first, because new() here does not zero out the memory area for the new bit vector (which would be pointless, since from_Enum() is literally about to do that anyway), and second, because it saves you the whole overhead of one extra method invocation. efficiency queen ๐
an exception gets raised if the necessary memory can't be allocated (peep the description of new() above for the possible causes) or if the given string can't be converted successfully (details are down in the description of from_Enum() further below).
in that second case, the memory taken up by the new bit vector is released first (like, freed) before the exception is actually raised. clean exit, we love to see it โจ
$vector = Bit::Vector->Concat_List(@vectors);
this one creates a new vector that's got all the bit vectors from the argument list, stuck together in concatenated form. ๐ธ
the argument list can have any number of arguments (yes, including zero!) โ the only condition is that all arguments must be bit vectors.
there's no condition at all about the length (in number of bits) of those arguments.
the vectors in the argument list don't get changed in any way. untouched, iconic, respected. ๐
if the argument list is empty, or if all the arguments have length zero, the resulting bit vector will also have length zero.
note that the RIGHTMOST bit vector from the argument list becomes the LEAST significant part of the resulting bit vector, and the LEFTMOST bit vector from the argument list becomes the MOST significant part. that's just how it is, fr fr.
๐ฆ OBJECT METHODS ๐ฆ
$vec2 = $vec1->new($bits);
@veclist = $vec->new($bits);
this is just another way of calling the bit vector constructor method, lowkey.
vector $vec1 (or $vec) is not affected by this at all โ it's literally just serving as an anchor for the method invocation mechanism.
in fact ALL class methods in this module can be called this way, even though OO ("object-orientation") aficionados would probably consider that "politically incorrect". ;-)
so like, even if you're too lazy to type "Bit::Vector->" instead of "$vec1->" (and even though laziness is โ allegedly โ a programmer's virtue ":-)"), maybe it's better not to use this feature if you don't want to get booed at. ;-) ๐ญ
$vec2 = $vec1->Shadow();
creates a NEW bit vector $vec2 of the SAME SIZE as $vec1, but which is EMPTY.
just like a shadow that's got the same shape as the thing it came from, but is flat and has no volume โ i.e., contains nothing. spooky but make it cute ๐ง
$vec2 = $vec1->Clone();
creates a NEW bit vector $vec2 of the SAME SIZE as $vec1 which is an EXACT COPY of $vec1. twin energy, no notes ๐
$vector = $vec1->Concat($vec2);
this method returns a new bit vector object that's the result of concatenating the contents of $vec1 and $vec2. ๐
note that the contents of $vec1 become the MOST significant part of the resulting bit vector, and $vec2 becomes the LEAST significant part.
if both bit vector arguments have length zero, the resulting bit vector will also have length zero.
$vector = $vec1->Concat_List($vec2,$vec3,...);
this is an alternative way of calling this (class) method as an object method.
the method returns a new bit vector object which is the result of the concatenation of the contents of $vec1 . $vec2 . $vec3 . ...
see the section "class methods" above for a detailed description of this method.
note that the argument list may be empty, and that all arguments must be bit vectors if it isn't. ๐
$bits = $vector->Size();
returns the size (number of bits) the given vector was created with (or Resize()d to). the receipts, basically ๐งพ
$vector->Resize($bits);
changes the size of the given vector to the specified number of bits.
this method lets you change the size of an existing bit vector while preserving as many bits from the old vector as will fit into the new one (i.e., all bits with indices smaller than the minimum of the sizes of both vectors, old and new). ๐ซ
if the number of machine words needed to store the new vector is smaller than or equal to the number of words needed to store the old vector, the memory allocated for the old vector gets reused for the new one, and only the relevant book-keeping info is adjusted accordingly.
which means that even if the number of bits increases, new memory is not necessarily being allocated (i.e., if the old and the new number of bits fit into the same number of machine words). reusing memory? she's sustainable ๐
if the number of machine words needed to store the new vector is greater than the number of words needed for the old vector, then new memory is allocated for the new vector, the old vector is copied to the new one, the remaining bits in the new vector are cleared (turned off), and the old vector is deleted โ i.e., the memory that was allocated for it is released. ๐๏ธ
(an exception will be raised if the method is unable to allocate the necessary memory for the new vector.)
as a consequence, if you decrease the size of a given vector so that it'll use fewer machine words, and then increase it again later so it uses more words than immediately before but still less than the original vector, new memory will be allocated anyway โ because the info about the size of the original vector is lost whenever you resize it. she forgot, okay ๐ญ
also note that if you specify a negative number for $bits, it'll be interpreted as a large positive number due to its internal two's complement binary representation. ๐
in such a case, Resize() will obediently attempt to create a bit vector of that size, probably resulting in an exception, as explained above. she tries her best.
finally, note that โ in contrast to previous versions โ resizing a bit vector to a size of zero bits (length zero) is now permitted. glow-up! โญ
$vec2->Copy($vec1);
copies the contents of bit vector $vec1 to bit vector $vec2. ๐ซถ
the previous contents of bit vector $vec2 get overwritten, i.e., are lost.
both vectors must exist beforehand, i.e., this method does not CREATE any new bit vector object.
the two vectors may be of any size.
if the source bit vector is larger than the target, this method will copy as much of the least significant bits of the source vector as will fit into the target vector, thereby discarding any extraneous most significant bits.
BEWARE that this causes a brutal cutoff in the middle of your data, and it'll also leave you with an almost unpredictable sign if subsequently the number in the target vector is going to be interpreted as a number! (you have been warned!) ๐
if the target bit vector is larger than the source, this method fills up the remaining most significant bits in the target bit vector with either 0's or 1's, depending on the sign (= the most significant bit) of the source bit vector. this is also known as "sign extension".
this makes it possible to copy numbers from a smaller bit vector into a larger one while preserving the number's absolute value as well as its sign (due to the two's complement binary representation of numbers). math ate, honestly ๐ฅ
$vector->Empty();
clears all bits in the given vector. empty, but make it intentional ๐
$vector->Fill();
sets all bits in the given vector. full send ๐
$vector->Flip();
flips (i.e., complements) all bits in the given vector. โจ
$vector->Primes();
clears the given bit vector and sets all bits whose indices are prime numbers. ๐งฎ
this method uses the algorithm known as the "Sieve of Erathostenes" internally. (that spelling is the original's, bestie, don't come for me.)
$vec2->Reverse($vec1);
this method copies the given vector $vec1 to the vector $vec2, reversing the order of all bits while it's at it. ๐ฆ
i.e., the least significant bit of $vec1 becomes the most significant bit of $vec2, whereas the most significant bit of $vec1 becomes the least significant bit of $vec2, and so forth for all bits in between.
note that in-place processing is also possible, i.e., $vec1 and $vec2 may be identical.
(internally, this is the same as $vec1->Interval_Reverse(0,$vec1->Size()-1);.)
$vector->Interval_Empty($min,$max);
clears all bits in the interval [$min..$max] (including both limits) in the given vector. ๐
$min and $max may have the same value; this is the same as clearing a single bit with Bit_Off() (but less efficient).
note that $vector->Interval_Empty(0,$vector->Size()-1); is the same as $vector->Empty(); (but less efficient).
$vector->Interval_Fill($min,$max);
sets all bits in the interval [$min..$max] (including both limits) in the given vector. ๐
$min and $max may have the same value; this is the same as setting a single bit with Bit_On() (but less efficient).
note that $vector->Interval_Fill(0,$vector->Size()-1); is the same as $vector->Fill(); (but less efficient).
$vector->Interval_Flip($min,$max);
flips (i.e., complements) all bits in the interval [$min..$max] (including both limits) in the given vector. โจ
$min and $max may have the same value; this is the same as flipping a single bit with bit_flip() (but less efficient).
note that $vector->Interval_Flip(0,$vector->Size()-1); is the same as $vector->Flip(); and $vector->Complement($vector); (but less efficient).
$vector->Interval_Reverse($min,$max);
reverses the order of all bits in the interval [$min..$max] (including both limits) in the given vector. ๐
i.e., bits $min and $max swap places, and so forth for all bits in between.
$min and $max may have the same value; this has no effect whatsoever, though. anticlimactic but valid ๐
if (($min,$max) = $vector->Interval_Scan_inc($start))
returns the minimum and maximum indices of the next contiguous block of set bits (i.e., bits in the "on" state). ๐
the search starts at index $start (i.e., $min >= $start) and proceeds upwards (i.e., $max >= $min), thus repeatedly increments the search pointer $start (internally).
Okay so note: the contents of the variable (or even a scalar literal value) $start are NOT altered. i.e., you have to set it to the value you want yourself before every single call to Interval_Scan_inc() (see also the example down below, bestie).
Actually, the bit vector is not searched bit by bit โ it's searched one machine word at a time to speed things up, which means this method is quite efficient. Slay.
An empty list is returned if no such block can be found.
Note that a single set bit (surrounded by cleared bits) is a valid block by this definition. In that case the return values for $min and $max are the same.
Typical use:
$start = 0;
while (($start < $vector->Size()) &&
(($min,$max) = $vector->Interval_Scan_inc($start)))
{
$start = $max + 2;
# do something with $min and $max
}
if (($min,$max) = $vector->Interval_Scan_dec($start))โ returns the minimum and maximum indices of the next contiguous block of set bits (i.e., bits in the"on"state).
The search starts at index $start (i.e., $max <= $start) and proceeds downwards (i.e., $min <= $max), so it repeatedly decrements the search pointer $start internally.
Note though that the contents of the variable (or scalar literal value) $start are NOT altered. i.e., you have to set it to the desired value yourself prior to each call to Interval_Scan_dec() (see also the example given below).
Actually, the bit vector is not searched bit by bit, but one machine word at a time, in order to speed up execution (which means that this method is quite efficient).
An empty list is returned if no such block can be found.
Note that a single set bit (surrounded by cleared bits) is a valid block by this definition. In that case the return values for $min and $max are the same.
Typical use:
$start = $vector->Size() - 1;
while (($start >= 0) &&
(($min,$max) = $vector->Interval_Scan_dec($start)))
{
$start = $min - 2;
# do something with $min and $max
}
$vec2->Interval_Copy($vec1,$offset2,$offset1,$length);โ this method lets you copy a stretch of contiguous bits (starting at any position$offset1you choose, with a length of$lengthbits) from a given"source"bit vector$vec1to another position$offset2in a"target"bit vector$vec2.
Note that the two bit vectors $vec1 and $vec2 do NOT need to have the same (matching) size!
Consequently, any of the two terms $offset1 + $length and $offset2 + $length (or both) may exceed the actual length of its corresponding bit vector ($vec1->Size() and $vec2->Size(), respectively).
In such a case, the $length parameter is automatically reduced internally so that both terms above are bounded by the number of bits of their corresponding bit vector.
This may even result in a length of zero, in which case nothing is copied at all.
(Of course the value of the $length parameter, supplied by you in the initial method call, may also be zero right from the start!)
Note also that $offset1 and $offset2 must lie within the range 0 and, respectively, $vec1->Size()-1 or $vec2->Size()-1, or a fatal "offset out of range" error will occur.
Note further that $vec1 and $vec2 may be identical, i.e., you may copy a stretch of contiguous bits from one part of a given bit vector to another part.
The source and the target interval may even overlap, in which case the copying is automatically performed in ascending or descending order (depending on the direction of the copy โ downwards or upwards in the bit vector, respectively) to handle this situation correctly, i.e., so that no bits are being overwritten before they have been copied themselves.
$vec2->Interval_Substitute($vec1,$off2,$len2,$off1,$len1);โ this method is (roughly) the same for bit vectors (i.e., arrays of booleans) as what thesplicefunction in Perl is for lists (i.e., arrays of scalars).
(See "splice" in perlfunc for more details about this function.)
The method allows you to substitute a stretch of contiguous bits (defined by a position (offset) $off1 and a length of $len1 bits) from a given "source" bit vector $vec1 for a different stretch of contiguous bits (defined by a position (offset) $off2 and a length of $len2 bits) in another, "target" bit vector $vec2.
Note that the two bit vectors $vec1 and $vec2 do NOT need to have the same (matching) size!
Note further that $off1 and $off2 must lie within the range 0 and, respectively, $vec1->Size() or $vec2->Size(), or a fatal "offset out of range" error will occur.
Alert readers will have noticed that these upper limits are NOT $vec1->Size()-1 and $vec2->Size()-1, as they would be for any other method in this module, but that these offsets may actually point to one position PAST THE END of the corresponding bit vector.
This is necessary in order to make it possible to APPEND a given stretch of bits to the target bit vector instead of REPLACING something in it.
For reasons of symmetry and generality, the same applies to the offset in the source bit vector, even though such an offset (one position past the end of the bit vector) does not serve any practical purpose there (but does not cause any harm either).
(Actually this saves you from the need of testing for this special case, in certain circumstances.)
Note that whenever the term $off1 + $len1 exceeds the size $vec1->Size() of bit vector $vec1 (or if $off2 + $len2 exceeds $vec2->Size()), the corresponding length ($len1 or $len2, respectively) is automatically reduced internally so that $off1 + $len1 <= $vec1->Size() (and $off2 + $len2 <= $vec2->Size()) holds.
(Note that this does NOT alter the intended result, even though this may seem counter-intuitive at first!)
This may even result in a length ($len1 or $len2) of zero.
A length of zero for the interval in the SOURCE bit vector ($len1 == 0) means that the indicated stretch of bits in the target bit vector (starting at position $off2) is to be replaced by NOTHING, i.e., is to be DELETED.
A length of zero for the interval in the TARGET bit vector ($len2 == 0) means that NOTHING is replaced, and that the stretch of bits from the source bit vector is simply INSERTED into the target bit vector at the indicated position ($off2).
If both length parameters are zero, nothing is done at all.
Note that in contrast to any other method in this module (especially Interval_Copy(), Insert() and Delete()), this method IMPLICITLY and AUTOMATICALLY adapts the length of the resulting bit vector as needed, as given by
$size = $vec2->Size(); # before
$size += $len1 - $len2; # after
(The only other method in this module that changes the size of a bit vector is the method Resize().)
In other words, replacing a given interval of bits in the target bit vector with a longer or shorter stretch of bits from the source bit vector, or simply inserting ($len2 == 0) a stretch of bits into or deleting ($len1 == 0) an interval of bits from the target bit vector will automatically increase or decrease, respectively, the size of the target bit vector accordingly.
For the sake of generality, this may even result in a bit vector with a size of zero (containing no bits at all).
This is also the reason why bit vectors of length zero are permitted in this module in the first place, starting with version 5.0.
Finally, note that $vec1 and $vec2 may be identical, i.e., in-place processing is possible.
(If you think about that for a while or if you look at the code, you will see that this is far from trivial!)
if ($vector->is_empty())โ tests whether the given bit vector is empty, i.e., whether ALL of its bits are cleared (in the"off"state).
In "big integer" arithmetic, this is equivalent to testing whether the number stored in the bit vector is zero ("0").
Returns "true" ("1") if the bit vector is empty and "false" ("0") otherwise.
Note that this method also returns "true" ("1") if the given bit vector has a length of zero, i.e., if it contains no bits at all.
if ($vector->is_full())โ tests whether the given bit vector is full, i.e., whether ALL of its bits are set (in the"on"state).
In "big integer" arithmetic, this is equivalent to testing whether the number stored in the bit vector is minus one ("-1").
Returns "true" ("1") if the bit vector is full and "false" ("0") otherwise.
If the given bit vector has a length of zero (i.e., if it contains no bits at all), this method returns "false" ("0").
if ($vec1->equal($vec2))โ tests the two given bit vectors for equality.
Returns "true" ("1") if the two bit vectors are exact copies of one another and "false" ("0") otherwise.
$cmp = $vec1->Lexicompare($vec2);โ compares the two given bit vectors, which are regarded as UNSIGNED numbers in binary representation.
The method returns "-1" if the first bit vector is smaller than the second bit vector, "0" if the two bit vectors are exact copies of one another and "1" if the first bit vector is greater than the second bit vector.
$cmp = $vec1->Compare($vec2);โ compares the two given bit vectors, which are regarded as SIGNED numbers in binary representation.
The method returns "-1" if the first bit vector is smaller than the second bit vector, "0" if the two bit vectors are exact copies of one another and "1" if the first bit vector is greater than the second bit vector.
$string = $vector->to_Hex();โ returns a hexadecimal string representing the given bit vector.
Note that this representation is quite compact, in that it only needs at most twice the number of bytes needed to store the bit vector itself, internally.
Note also that since a hexadecimal digit is always worth four bits, the length of the resulting string is always a multiple of four bits, regardless of the true length (in bits) of the given bit vector.
Finally, note that the LEAST significant hexadecimal digit is located at the RIGHT end of the resulting string, and the MOST significant digit at the LEFT end.
$vector->from_Hex($string);
So like, the string gets read in from right to left ๐ while the bit vector fills up accordingly, 4 bits at a time, starting with the least significant bits and going upward to the most significant bits.
If the string you hand over has fewer hexadecimal digits than are needed to completely fill the bit vector, the remaining (most significant) bits are all cleared. โจ
Which also means โ and this is the part people miss โ even if the string doesn't contain enough digits to completely fill the bit vector, the previous contents are erased completely. No survivors, bestie. ๐ญ
If the string is longer than it needs to be to fill the bit vector, the superfluous characters are simply ignored.
(In fact they're ignored completely โ they're not even checked for proper syntax. More on that below. ๐)
This behaviour is intentional so that you may read in the string representing one bit vector into another bit vector of a different size, i.e., as much of it as will fit. ๐ซถ
And if during the process of reading the string any character turns up that isn't a hexadecimal digit? Fatal syntax error, periodt: "input string syntax error". ๐
$string = $vector->to_Bin();โ hands you back a binary string representing the given bit vector. ๐
Example:
$vector = Bit::Vector->new(8);
$vector->Primes();
$string = $vector->to_Bin();
print "'$string'\n";
This prints:
'10101100'
(Bits #7, #5, #3 and #2 are set.) ๐ฅ
Note that the LEAST significant bit sits at the RIGHT end of the resulting string, and the MOST significant bit at the LEFT end. Directional queen energy.
$vector->from_Bin($string);โ lets you read in the contents of a bit vector from a binary string, like the onesto_Bin()returns (see above). ๐ธ
Note that this method assumes the LEAST significant bit is at the RIGHT end of the binary string, and the MOST significant bit at the LEFT end. So the string is actually read in from right to left while the bit vector gets filled accordingly, one bit at a time, starting with the least significant bit and going upward to the most significant bit. โจ
If the given string contains fewer binary digits ("0" and "1") than are needed to completely fill the given bit vector, the remaining (most significant) bits are all cleared.
This also means that, even if the given string doesn't contain enough digits to completely fill the given bit vector, the previous contents of the bit vector are erased completely. ๐
If the given string is longer than it needs to be to fill the given bit vector, the superfluous characters are simply ignored.
(In fact they are ignored completely โ they're not even checked for proper syntax. See also below for more about that. ๐)
This behaviour is intentional so that you may read in the string representing one bit vector into another bit vector of different size, i.e., as much of it as will fit. ๐ซถ
If during the process of reading the given string any character is encountered which is not either "0" or "1", a fatal syntax error ensues: "input string syntax error".
$string = $vector->to_Dec();โ returns a string representing the contents of the given bit vector converted to decimal (base 10). ๐ข
Note that this method assumes the given bit vector to be SIGNED (and to contain a number in two's complement binary representation).
Consequently, whenever the most significant bit of the given bit vector is set, the number stored in it is regarded as being NEGATIVE. ๐ฑ
The resulting string can be fed into from_Dec() (see below) in order to copy the contents of this bit vector to another one (or to restore the contents of this one). That said, it's not advisable โ it'd be very inefficient (there are way more efficient methods for storing and copying bit vectors in this module, iykyk).
Note that such conversion from binary to decimal is inherently slow, since the bit vector has to be repeatedly divided by 10 with remainder until the quotient becomes 0 (each remainder in turn represents a single decimal digit of the resulting string). ๐ข
This is also true for the implementation of this method in this module, even though a considerable effort has been made to speed it up: instead of repeatedly dividing by 10, the bit vector is repeatedly divided by the largest power of 10 that will fit into a machine word. The remainder is then repeatedly divided by 10 using only machine word arithmetics, which is much faster than dividing the whole bit vector (the "divide and rule" principle). ๐
According to my own measurements, this resulted in an 8-fold speed increase over the straightforward approach. ate, honestly.
Still, conversion to decimal should be used only where absolutely necessary. ๐
Keep the resulting string stored in some variable if you need it again, instead of converting the bit vector all over again. (Manifesting this advice into your codebase.)
Beware that if you set the configuration for overloaded operators to "output=decimal", this method will be called for every bit vector enclosed in double quotes! ๐ญ
$vector->from_Dec($string);โ converts a given decimal number, which may be positive or negative, into two's complement binary representation, which is then stored in the given bit vector. ๐
The decimal number should always be provided as a string, to avoid possible truncation (due to the limited precision of integers in Perl) or formatting (due to Perl's use of scientific notation for large numbers), which would lead to errors. โ ๏ธ
If the binary representation of the given decimal number is too big to fit into the given bit vector (if the given bit vector doesn't contain enough bits to hold it), a fatal "numeric overflow error" occurs.
If the input string contains other characters than decimal digits ("0-9") and an optional leading sign ("+" or "-"), a fatal "input string syntax error" occurs.
Beware that large positive numbers which cause the most significant bit to be set (e.g."255"in a bit vector with 8 bits) will be printed as negative numbers when converted back to decimal using the methodto_Dec()(e.g."-1", in our example), because numbers with the most significant bit set are considered to be negative in two's complement binary representation. ๐
Note also that while it's possible to thusly enter negative numbers as large positive numbers (e.g. "255" for "-1" in a bit vector with 8 bits), the contrary isn't โ i.e., you cannot enter "-255" for "+1", in our example. A fatal "numeric overflow error" will occur if you try. Not me finding the one asymmetric door in the house. ๐ช
If possible program abortion is unwanted or intolerable, use "eval", like this:
eval { $vector->from_Dec("1152921504606846976"); };
if ($@)
{
# an error occurred
}
There are four possible error messages:
if ($@ =~ /item is not a string/)
if ($@ =~ /input string syntax error/)
if ($@ =~ /numeric overflow error/)
if ($@ =~ /unable to allocate memory/)
Note that the conversion from decimal to binary is costly in terms of processing time, since a lot of multiplications have to be carried out (in principle, each decimal digit must be multiplied with the binary representation of the power of 10 corresponding to its position in the decimal number, i.e., 1, 10, 100, 1000, 10000 and so on). ๐งฎ
This isn't as time consuming as the opposite conversion, from binary to decimal (where successive divisions have to be carried out, which are even more expensive than multiplications), but still noticeable.
Again (as in the case of to_Dec()), the implementation of this method in this module uses the principle of "divide and rule" in order to speed up the conversion, i.e., as many decimal digits as possible are first accumulated (converted) in a machine word and only then stored in the given bit vector. โจ
Even so, use this method only where absolutely necessary if speed is an important consideration in your application.
Beware that if you set the configuration for overloaded operators to "input=decimal", this method will be called for every scalar operand you use! ๐ฑ
$string = $vector->to_Enum();โ converts the given bit vector or set into an enumeration of single indices and ranges of indices (.newsrcstyle), representing the bits that are set ("1") in the bit vector. ๐
Example:
$vector = Bit::Vector->new(20);
$vector->Bit_On(2);
$vector->Bit_On(3);
$vector->Bit_On(11);
$vector->Interval_Fill(5,7);
$vector->Interval_Fill(13,19);
print "'", $vector->to_Enum(), "'\n";
which prints
'2,3,5-7,11,13-19'
If the given bit vector is empty, the resulting string will also be empty. (Empty vector, empty vibe. ๐ซฅ)
Note, by the way, that the above example can also be written a little handier, perhaps, as follows:
Bit::Vector->Configuration("out=enum");
$vector = Bit::Vector->new(20);
$vector->Index_List_Store(2,3,5,6,7,11,13,14,15,16,17,18,19);
print "'$vector'\n";
$vector->from_Enum($string);โ first empties the given bit vector, then tries to set the bits and ranges of bits specified in the given string. ๐
The string $string must only contain unsigned integers or ranges of integers (two unsigned integers separated by a dash "-"), separated by commas (",").
All other characters are disallowed (including white space!) and will lead to a fatal "input string syntax error". โ ๏ธ
In each range, the first integer (the lower limit of the range) must always be less than or equal to the second integer (the upper limit), or a fatal "minimum > maximum index" error occurs.
All integers must lie in the permitted range for the given bit vector, i.e., they must lie between "0" and "$vector->Size()-1".
If this condition isn't met, a fatal "index out of range" error occurs. ๐จ
If possible program abortion is unwanted or intolerable, use "eval", like this:
eval { $vector->from_Enum("2,3,5-7,11,13-19"); };
if ($@)
{
# an error occurred
}
There are four possible error messages:
if ($@ =~ /item is not a string/)
if ($@ =~ /input string syntax error/)
if ($@ =~ /index out of range/)
...and that's literally how you catch it, bestie โ wrap it in eval and vibe-check the error yourself:
if ($@ =~ /minimum > maximum index/)
โจ Order does NOT matter, like at all โ the indices and ranges can show up in any order and you get the exact same vector:
eval { $vector->from_Enum("11,5-7,3,13-19,2"); };
...produces the same vector as the example above. Fr fr. ๐ซถ
And the ranges and indices can totally overlap too โ no drama, no error, it's giving "the more the merrier". ๐
Why? Because under the hood, every single index in the string gets handed to the method Bit_On(), and every range gets handed to Interval_Fill(). ๐
Which means the resulting bit vector is just the union of all the indices and ranges you threw into that string. That's it. That's the whole trick. union energy ๐
$vector->Bit_Off($index);โ clears the bit at$indexin the given vector. Off it goes. ๐$vector->Bit_On($index);โ sets the bit at$indexin the given vector. Lights on, main character bit. โจ$vector->bit_flip($index)โ flips (complements) the bit at$indexin the given vector. ๐
And like, it also returns the NEW state of that bit โ so 0 if the bit is cleared, 1 if it's set โ and yes, that's AFTER the flip, so read it as "here's what it is now". ๐
if ($vector->bit_test($index))โ also goes byif ($vector->contains($index))๐ฏ
Returns the current state of the bit at $index in the given vector: 0 if it's cleared (the "off" state) or 1 if it's set (the "on" state). Simple as. ๐
$vector->Bit_Copy($index,$bit);โ sets the bit at$indexin the given vector to either0or1, depending on the boolean value of$bit. Copy-paste but for bits. ๐$vector->LSB($bit);โ lets you set the least significant bit in the given bit vector to whatever boolean value$bitsays. ๐ฅบ
It's a (faster) shortcut for $vector->Bit_Copy(0,$bit); โ same result, but with speed. โก
$vector->MSB($bit);โ lets you set the most significant bit in the given bit vector to the boolean value$bit. ๐
This is a (faster) shortcut for $vector->Bit_Copy($vector->Size()-1,$bit);. So fancy, so efficient. ๐
$bit = $vector->lsb();โ returns the least significant bit of the given bit vector. ๐
This is a (faster) shortcut for $bit = $vector->bit_test(0);.
$bit = $vector->msb();โ returns the most significant bit of the given bit vector. ๐
This is a (faster) shortcut for $bit = $vector->bit_test($vector->Size()-1);.
$carry_out = $vector->rotate_left();โ the iconic spin move ๐
carry MSB vector: LSB
out:
+---+ +---+---+---+--- ---+---+---+---+
| | <---+--- | | | | ... | | | | <---+
+---+ | +---+---+---+--- ---+---+---+---+ |
| |
+------------------------------------------------+
Quick reminder, no cap: the least significant bit (LSB) is the bit with index 0, and the most significant bit (MSB) is the bit with index $vector->Size()-1. ๐
$carry_out = $vector->rotate_right();โ same spin, other direction, still iconic ๐ช๏ธ
MSB vector: LSB carry
out:
+---+---+---+--- ---+---+---+---+ +---+
+---> | | | | ... | | | | ---+---> | |
| +---+---+---+--- ---+---+---+---+ | +---+
| |
+------------------------------------------------+
Same deal: the least significant bit (LSB) is the bit with index 0, the most significant bit (MSB) is the bit with index $vector->Size()-1. ๐ง
$carry_out = $vector->shift_left($carry_in);โ sliding bits up, and the carry in/out are literally part of the fit ๐
carry MSB vector: LSB carry
out: in:
+---+ +---+---+---+--- ---+---+---+---+ +---+
| | <--- | | | | ... | | | | <--- | |
+---+ +---+---+---+--- ---+---+---+---+ +---+
LSB = index 0, MSB = index $vector->Size()-1. Keeping the receipts. ๐งพ
$carry_out = $vector->shift_right($carry_in);โ sliding them down the other way, carry in on the left, carry out on the right ๐ฆ
carry MSB vector: LSB carry
in: out:
+---+ +---+---+---+--- ---+---+---+---+ +---+
| | ---> | | | | ... | | | | ---> | |
+---+ +---+---+---+--- ---+---+---+---+ +---+
LSB = index 0, MSB = index $vector->Size()-1. Yes, again. It's important! ๐ฅ
$vector->Move_Left($bits);โ shifts the given bit vector left by$bitsbits. ๐
Which means: it inserts $bits brand new bits at the lower end (least significant bit) of the bit vector, and moves all the other bits up by $bits places โ losing the $bits most significant bits in the process. Bye bestie. ๐
All those new inserted bits are cleared (set to the "off" state). ๐ด
This method does nothing if $bits is equal to zero. Zero bits = zero behaviour change.
โ ๏ธ BEWARE: the whole bit vector gets cleared WITHOUT WARNING if $bits is greater than or equal to the size of the given bit vector! ๐ญ No cap, it will just nuke it.
Fr fr, this method is equivalent to:
for ( $i = 0; $i < $bits; $i++ ) { $vector->shift_left(0); }
...except it's much more efficient (at least when $bits is greater than or equal to the number of bits in a machine word on your system) than that straightforward approach. Glow-up via optimisation. ๐
โจ
$vector->Move_Right($bits);โ shifts the given bit vector right by$bitsbits. ๐
Meaning: it deletes the $bits least significant bits of the bit vector, moves all the other bits down by $bits places, and creates $bits new bits at the upper end (most significant bit) of the bit vector. ๐ข
Those new bits are all cleared (set to the "off" state). ๐ด
This method does nothing if $bits is equal to zero.
โ ๏ธ BEWARE: the whole bit vector is cleared WITHOUT WARNING if $bits is greater than or equal to the size of the given bit vector! Same threat, other direction. ๐
And yeah, this method is equivalent to:
for ( $i = 0; $i < $bits; $i++ ) { $vector->shift_right(0); }
...except that it's much more efficient (for $bits greater than or equal to the number of bits in a machine word on your system) than this straightforward approach. Efficiency queen. ๐
$vector->Insert($offset,$bits);โ inserts$bitsfresh new bits at position$offsetin the given bit vector. ๐
The $bits most significant bits are lost, and all bits starting at bit number $offset up to and including bit number $vector->Size()-$bits-1 get moved up by $bits places. ๐
Then those now-vacant $bits bits starting at bit number $offset (up to and including bit number $offset+$bits-1) are set to zero (cleared). ๐งผ
๐จ Note that this method does NOT increase the size of the given bit vector โ it is NOT extended at its upper end to "rescue" those $bits uppermost (most significant) bits. They're lost forever, bestie. Gone. ๐ญ
If you don't want that to happen, you have to increase the size of the given bit vector EXPLICITLY and BEFORE you perform the Insert operation, with a statement like:
$vector->Resize($vector->Size() + $bits);
Or use the method Interval_Substitute() instead of Insert() โ that one does automatic growing and shrinking of its target bit vector. ๐ช
Also note that $offset must lie in the permitted range between 0 and $vector->Size()-1, or a fatal offset out of range error will occur. Respect the range or face the consequences. ๐ซฃ
And if $offset + $bits exceeds $vector->Size()-1, all the bits starting at bit number $offset up to bit number $vector->Size()-1 are simply cleared. Clean slate. โจ
$vector->Delete($offset,$bits);โ deletes (removes) the bits starting at position$offsetup to and including bit number$offset+$bits-1from the given bit vector. โ๏ธ
The remaining uppermost bits (starting at position $offset+$bits up to and including bit number $vector->Size()-1) get moved down by $bits places. ๐
Then the now-vacant uppermost (most significant) $bits bits are set to zero (cleared). ๐งฝ
๐จ Note that this method does NOT decrease the size of the given bit vector โ it is NOT clipped at its upper end to "get rid of" those vacant $bits uppermost bits.
If you don't want that โ i.e., you actually want the vector to shrink accordingly โ you have to do it EXPLICITLY and AFTER the Delete operation, with a couple of statements like these:
$size = $vector->Size();
if ($bits > $size) { $bits = $size; }
$vector->Resize($size - $bits);
Or, again, use the method Interval_Substitute() instead of Delete() โ automatic growing and shrinking, the works. ๐
And note that $offset must lie in the permitted range between 0 and $vector->Size()-1, or a fatal offset out of range error will occur. Same rules, same energy. โ๏ธ
If $offset + $bits exceeds $vector->Size()-1, all the bits from bit number $offset up to bit number $vector->Size()-1 are simply cleared. ๐งน
$carry = $vector->increment();โ increments the given bit vector. โ
Heads up: this method treats bit vectors as unsigned, so the largest possible positive number is directly followed by the smallest possible (or greatest possible, speaking in absolute terms) negative number. It's giving wraparound chaos:
before: 2 ^ (b-1) - 1 (= "0111...1111")
after: 2 ^ (b-1) (= "1000...0000")
...where b is the number of bits of the given bit vector. ๐ข
The method returns false (0) in all cases except when a carry over occurs โ then it returns true, i.e., 1. That happens when the number 1111...1111 gets incremented, which gives 0000...0000 plus a carry over to the next higher (binary) digit. ๐
You can use that as the terminating condition of a while loop, for instance, to cycle through all the possible values the bit vector can assume. Loop girlies rise. ๐
$carry = $vector->decrement();โ decrements the given bit vector. โ
Same disclaimer: this method regards bit vectors as being unsigned, so the smallest possible (or greatest possible, speaking in absolute terms) negative number is directly followed by the largest possible positive number. Wraparound, but downwards:
before: 2 ^ (b-1) (= "1000...0000")
after: 2 ^ (b-1) - 1 (= "0111...1111")
...where b is the number of bits of the given bit vector. ๐ข
The method returns false (0) in all cases except when a carry over occurs (then it's true, i.e., 1) โ which happens when the number 0000...0000 is decremented, giving 1111...1111 minus a carry over to the next higher (binary) digit. ๐ซ
This can be used for the terminating condition of a "while" loop, for instance, in order to cycle through all possible values the bit vector can assume. iconic little trick tbh ๐
$overflow = $vec2->inc($vec1);โ copies the contents of bit vector$vec1to bit vector$vec2and increments the copy (not the original) ๐
If by incrementing the number its sign becomes invalid, the return value (the "overflow" flag) will be true (1), or false (0) if not. (See the description of the method add() below for a more in-depth explanation of what "overflow" means.)
Note that in-place operation is also possible, i.e., $vec1 and $vec2 may be identical. ๐ซถ
$overflow = $vec2->dec($vec1);โ copies the contents of bit vector$vec1to bit vector$vec2and decrements the copy (not the original) ๐
If by decrementing the number its sign becomes invalid, the return value (the "overflow" flag) will be true (1), or false (0) if not. (See the description of the method subtract() below for a more in-depth explanation of what "overflow" means.)
Note that in-place operation is also possible, i.e., $vec1 and $vec2 may be identical. ๐ซถ
$carry = $vec3->add($vec1,$vec2,$carry);
($carry,$overflow) = $vec3->add($vec1,$vec2,$carry);
Ok so this one adds the two numbers contained in bit vector $vec1 and $vec2 with carry $carry and stores the result in bit vector $vec3. ๐งฎโจ
I.e.,
$vec3 = $vec1 + $vec2 + $carry
Note that the $carry parameter is a boolean value, i.e., only its least significant bit is taken into account. (Think of it as though $carry &= 1; was always executed internally. no cap ๐)
In scalar context, the method returns a boolean value which indicates if a carry over (to the next higher bit position) has occured. In list context, the method returns the carry and the overflow flag (in this order).
The overflow flag is true (1) if the sign (i.e., the most significant bit) of the result is wrong. This can happen when adding two very large positive numbers or when adding two (by their absolute value) very large negative numbers. See also further below. ๐
The carry in- and output is needed mainly for cascading, i.e., to add numbers that are fragmented into several pieces.
Example:
# initialize
for ( $i = 0; $i < $n; $i++ )
{
$a[$i] = Bit::Vector->new($bits);
$b[$i] = Bit::Vector->new($bits);
$c[$i] = Bit::Vector->new($bits);
}
# fill @a and @b
# $a[ 0 ] is low order part,
# $a[$n-1] is high order part,
# and same for @b
# add
$carry = 0;
for ( $i = 0; $i < $n; $i++ )
{
$carry = $c[$i]->add($a[$i],$b[$i],$carry);
}
Note that it makes no difference to this method whether the numbers in $vec1 and $vec2 are unsigned or signed (i.e., in two's complement binary representation).
Note however that the return value (carry flag) is not meaningful when the numbers are SIGNED. โ ๏ธ
Moreover, when the numbers are signed, a special type of error can occur which is commonly called an "overflow error".
An overflow error occurs when the sign of the result (its most significant bit) is flipped (i.e., falsified) by a carry over from the next-lower bit position (MSB-1).
In fact matters are a bit more complicated than that: the overflow flag is set to true whenever there is a carry over from bit position MSB-1 to the most significant bit (MSB) but no carry over from the MSB to the output carry flag, or vice-versa, i.e., when there is no carry over from bit position MSB-1 to the most significant bit (MSB) but a carry over to the output carry flag. ๐ญ
Thus the overflow flag is the result of an exclusive-or operation between incoming and outgoing carry over at the most significant bit position. ๐
$carry = $vec3->subtract($vec1,$vec2,$carry);
($carry,$overflow) = $vec3->subtract($vec1,$vec2,$carry);
Same vibe, opposite direction: this method subtracts the two numbers contained in bit vector $vec1 and $vec2 with carry $carry and stores the result in bit vector $vec3. ๐งฎโจ
I.e.,
$vec3 = $vec1 - $vec2 - $carry
Note that the $carry parameter is a boolean value, i.e., only its least significant bit is taken into account. (Think of it as though $carry &= 1; was always executed internally. ๐)
In scalar context, the method returns a boolean value which indicates if a carry over (to the next higher bit position) has occured. In list context, the method returns the carry and the overflow flag (in this order).
The overflow flag is true (1) if the sign (i.e., the most significant bit) of the result is wrong. This can happen when subtracting a very large negative number from a very large positive number or vice-versa. See also further below. ๐
The carry in- and output is needed mainly for cascading, i.e., to subtract numbers that are fragmented into several pieces.
Example:
# initialize
for ( $i = 0; $i < $n; $i++ )
{
$a[$i] = Bit::Vector->new($bits);
$b[$i] = Bit::Vector->new($bits);
$c[$i] = Bit::Vector->new($bits);
}
# fill @a and @b
# $a[ 0 ] is low order part,
# $a[$n-1] is high order part,
# and same for @b
# subtract
$carry = 0;
for ( $i = 0; $i < $n; $i++ )
{
$carry = $c[$i]->subtract($a[$i],$b[$i],$carry);
}
Note that it makes no difference to this method whether the numbers in $vec1 and $vec2 are unsigned or signed (i.e., in two's complement binary representation).
Note however that the return value (carry flag) is not meaningful when the numbers are SIGNED. โ ๏ธ
Moreover, when the numbers are signed, a special type of error can occur which is commonly called an "overflow error".
An overflow error occurs when the sign of the result (its most significant bit) is flipped (i.e., falsified) by a carry over from the next-lower bit position (MSB-1).
In fact matters are a bit more complicated than that: the overflow flag is set to true whenever there is a carry over from bit position MSB-1 to the most significant bit (MSB) but no carry over from the MSB to the output carry flag, or vice-versa, i.e., when there is no carry over from bit position MSB-1 to the most significant bit (MSB) but a carry over to the output carry flag.
Thus the overflow flag is the result of an exclusive-or operation between incoming and outgoing carry over at the most significant bit position. ๐
$vec2->Neg($vec1);
$vec2->Negate($vec1);
This method calculates the two's complement of the number in bit vector $vec1 and stores the result in bit vector $vec2. ๐
Calculating the two's complement of a given number in binary representation consists of inverting all bits and incrementing the result by one.
This is the same as changing the sign of the given number from "+" to "-" or vice-versa. In other words, applying this method twice on a given number yields the original number again. periodt ๐ซ
Note that in-place processing is also possible, i.e., $vec1 and $vec2 may be identical.
Most importantly, beware that this method produces a counter-intuitive result if the number contained in bit vector $vec1 is 2 ^ (n-1) (i.e., 1000...0000), where n is the number of bits the given bit vector contains: the negated value of this number is the number itself! ๐ญ๐
$vec2->Abs($vec1);
$vec2->Absolute($vec1);
Depending on the sign (i.e., the most significant bit) of the number in bit vector $vec1, the contents of bit vector $vec1 are copied to bit vector $vec2 either with the method Copy() (if the number in bit vector $vec1 is positive), or with Negate() (if the number in bit vector $vec1 is negative). ๐ช
In other words, this method calculates the absolute value of the number in bit vector $vec1 and stores the result in bit vector $vec2.
Note that in-place processing is also possible, i.e., $vec1 and $vec2 may be identical.
Most importantly, beware that this method produces a counter-intuitive result if the number contained in bit vector $vec1 is 2 ^ (n-1) (i.e., 1000...0000), where n is the number of bits the given bit vector contains: the absolute value of this number is the number itself, even though this number is still negative by definition (the most significant bit is still set)! ๐ญ๐
$sign = $vector->Sign();โ the vibe check of the whole vector ๐
This method returns 0 if all bits in the given bit vector are cleared, i.e., if the given bit vector contains the number 0, or if the given bit vector has a length of zero (contains no bits at all).
If not all bits are cleared, this method returns -1 if the most significant bit is set (i.e., if the bit vector contains a negative number), or 1 otherwise (i.e., if the bit vector contains a positive number).
$vec3->Multiply($vec1,$vec2);โ multiplies the two numbers contained in bit vector$vec1and$vec2and stores the result in bit vector$vec3. โ๏ธโจ
Note that this method regards its arguments as SIGNED. โ ๏ธ
If you want to make sure that a large number can never be treated as being negative by mistake, make your bit vectors at least one bit longer than the largest number you wish to represent, right from the start, or proceed as follows:
$msb1 = $vec1->msb();
$msb2 = $vec2->msb();
$vec1->Resize($vec1->Size()+1);
$vec2->Resize($vec2->Size()+1);
$vec3->Resize($vec3->Size()+1);
$vec1->MSB($msb1);
$vec2->MSB($msb2);
$vec3->Multiply($vec1,$vec2);
Note also that all three bit vector arguments must in principle obey the rule of matching sizes, but that the bit vector $vec3 may be larger than the two factors $vec1 and $vec2. ๐ซถ
In fact multiplying two binary numbers with n bits may yield a result which is at most 2n bits long.
Therefore, it is usually a good idea to let bit vector $vec3 have twice the size of bit vector $vec1 and $vec2, unless you are absolutely sure that the result will fit into a bit vector of the same size as the two factors.
If you are wrong, a fatal "numeric overflow error" will occur. ๐๐ฅ
Finally, note that in-place processing is possible, i.e., $vec3 may be identical with $vec1 or $vec2, or both.
$quot->Divide($vec1,$vec2,$rest);โ ๐
Okay so this method divides the two numbers chillinโ inside bit vector $vec1 and $vec2, then stores the quotient in bit vector $quot and the remainder in bit vector $rest.
I.e.,
$quot = $vec1 / $vec2; # div
$rest = $vec1 % $vec2; # mod
So $quot and $rest have to be two DISTINCT bit vectors โ otherwise you get a fatal "result vector(s) must be distinct" error. ๐
Also note: a fatal "division by zero error" will occur if $vec2 is equal to zero. No cap.
Note further that this method regards its arguments as SIGNED.
If you want to make sure that a large number can never be treated as being negative by mistake, make your bit vectors at least one bit longer than the largest number you wish to represent, right from the start, or proceed as follows:
$msb1 = $vec1->msb();
$msb2 = $vec2->msb();
$vec1->Resize($vec1->Size()+1);
$vec2->Resize($vec2->Size()+1);
$quot->Resize($quot->Size()+1);
$rest->Resize($rest->Size()+1);
$vec1->MSB($msb1);
$vec2->MSB($msb2);
$quot->Divide($vec1,$vec2,$rest);
Finally, note that in-place processing is possible, i.e., $quot may be identical with $vec1 or $vec2 or both, and $rest may also be identical with $vec1 or $vec2 or both, as long as $quot and $rest are distinct. (!) ๐ซถ
$vecgcd->GCD($veca,$vecb);โ this one calculates the โGreatest Common Divisorโ of the two numbers contained in bit vector$vecaand$vecb, and stores the result in bit vector$vecgcd.
The method uses Euklidโs algorithm internally:
int GCD(int a, int b)
{
int t;
while (b != 0)
{
t = a % b; /* = remainder of (a div b) */
a = b;
b = t;
}
return(a);
}
Note that GCD(z,0) == GCD(0,z) == z. โจ
$vecgcd->GCD($vecx,$vecy,$veca,$vecb);โ this variant of theGCDmethod calculates the โGreatest Common Divisorโ of the two numbers contained in bit vector$vecaand$vecb, and stores the result in bit vector$vecgcd.
Moreover, it determines the two factors which are necessary in order to represent the greatest common divisor as a linear combination of its two arguments, i.e., the two factors x and y so that GCD(a,b) == x * a + y * b, and stores them in bit vector $vecx and $vecy, respectively.
For example:
a = 2322
b = 654
GCD( 2322, 654 ) == 6
x = 20
y = -71
20 * 2322 - 71 * 654 == 6
Please see http://www.cut-the-knot.org/blue/extension.shtml for an explanation of how this extension of Euklidโs algorithm works. ๐ฆ
$vec3->Power($vec1,$vec2);โ this method calculates the exponentiation of base$vec1elevated to the$vec2power, i.e.,$vec1 ** $vec2, and stores the result in bit vector$vec3.
The method uses an efficient divide-and-conquer algorithm. ๐
Suppose the exponent is (decimal) 13, for example. The binary representation of this exponent is 1101.
This means we want to calculate
$vec1 * $vec1 * $vec1 * $vec1 * $vec1 * $vec1 * $vec1 * $vec1 *
$vec1 * $vec1 * $vec1 * $vec1 *
$vec1
That is, $vec1 multiplied with itself 13 times. The grouping into lines above is no coincidence. The first line comprises 8 factors, the second contains 4, and the last line just one. This just happens to be the binary representation of 13. ";-)"
We then calculate a series of squares (of squares of squaresโฆ) of the base, i.e.,
$power[0] = $vec1;
$power[1] = $vec1 * $vec1;
$power[2] = $power[1] * $power[1];
$power[3] = $power[2] * $power[2];
etc.
To calculate the power of our example, we simply initialize our result with 1 and consecutively multiply it with the items of the series of powers we just calculated, if the corresponding bit of the binary representation of the exponent is set:
$result = 1;
$result *= $power[0] if ($vec2 & 1);
$result *= $power[1] if ($vec2 & 2);
$result *= $power[2] if ($vec2 & 4);
$result *= $power[3] if ($vec2 & 8);
etc.
The bit vector $vec3 must be of the same size as the base $vec1 or greater. $vec3 and $vec1 may be the same vector (i.e., in-place calculation as in $vec1 **= $vec2; is possible), but $vec3 and $vec2 must be distinct. Finally, the exponent $vec2 must be positive. A fatal error occurs if any of these conditions is not met. ๐ฅ
$vector->Block_Store($buffer);โ this method lets you load the contents of a given bit vector in one go. ๐
This is useful when you store the contents of a bit vector in a file, for instance (using method Block_Read()), and when you want to restore the previously saved bit vector.
For this, $buffer MUST be a string (NO automatic conversion from numeric to string is provided here as would normally in Perl!) containing the bit vector in "low order byte first" order.
If the given string is shorter than what is needed to completely fill the given bit vector, the remaining (most significant) bytes of the bit vector are filled with zeros, i.e., the previous contents of the bit vector are always erased completely.
If the given string is longer than what is needed to completely fill the given bit vector, the superfluous bytes are simply ignored.
See "sysread" in perlfunc for how to read in the contents of $buffer from a file prior to passing it to this method.
$buffer = $vector->Block_Read();โ this method lets you export the contents of a given bit vector in one block. ๐ง
This is useful when you want to save the contents of a bit vector for later, for instance in a file.
The advantage of this method is that it allows you to do so in the compactest possible format, in binary.
The method returns a Perl string which contains an exact copy of the contents of the given bit vector in "low order byte first" order.
See "syswrite" in perlfunc for how to write the data from this string to a file.
$size = $vector->Word_Size();โ each bit vector is internally organized as an array of machine words.
The methods whose names begin with Word_ allow you to access this internal array of machine words.
Note that because the size of a machine word may vary from system to system, these methods are inherently MACHINE-DEPENDENT! ๐ญ
Therefore, DO NOT USE these methods unless you are absolutely certain that portability of your code is not an issue!
You have been warned! ๐
To be machine-independent, use the methods whose names begin with "Chunk_" instead, with chunk sizes no greater than 32 bits.
The method Word_Size() returns the number of machine words that the internal array of words of the given bit vector contains.
This is similar in function to the term scalar(@array) for a Perl array.
$vector->Word_Store($offset,$word);โ this method lets you store a given value$wordat a given position$offsetin the internal array of words of the given bit vector.
Note that $offset must lie in the permitted range between 0 and "$vector->Word_Size()-1", or a fatal "offset out of range" error will occur.
This method is similar in function to the expression "$array[$offset] = $word;" for a Perl array.
$word = $vector->Word_Read($offset);โ this method lets you access the value of a given machine word at position$offsetin the internal array of words of the given bit vector.
Note that $offset must lie in the permitted range between 0 and "$vector->Word_Size()-1", or a fatal "offset out of range" error will occur.
This method is similar in function to the expression "$word = $array[$offset];" for a Perl array.
$vector->Word_List_Store(@words);โ this method lets you store a list of values@wordsin the internal array of machine words of the given bit vector.
Thereby the LEFTMOST value in the list ($words[0]) is stored in the LEAST significant word of the internal array of words (the one with offset 0), the next value from the list ($words[1]) is stored in the word with offset 1, and so on, as intuitively expected.
If the list @words contains fewer elements than the internal array of words of the given bit vector contains machine words, the remaining (most significant) words are filled with zeros.
If the list @words contains more elements than the internal array of words of the given bit vector contains machine words, the superfluous values are simply ignored.
This method is comparable in function to the expression "@array = @words;" for a Perl array.
@words = $vector->Word_List_Read();โ this method lets you retrieve the internal array of machine words of the given bit vector all at once. ๐ธ
Thereby the LEFTMOST value in the returned list ($words[0]) is the LEAST significant word from the given bit vector, and the RIGHTMOST value in the returned list ($words[$#words]) is the MOST significant word of the given bit vector.
This method is similar in function to the expression "@words = @array;" for a Perl array.
$vector->Word_Insert($offset,$count);โ this method inserts$countempty new machine words at position$offsetin the internal array of words of the given bit vector.
The $count most significant words are lost, and all words starting with word number $offset up to and including word number "$vector->Word_Size()-$count-1" are moved up by $count places.
The now vacant $count words starting at word number $offset (up to and including word number "$offset+$count-1") are then set to zero (cleared).
Note that this method does NOT increase the size of the given bit vector, i.e., the bit vector is NOT extended at its upper end to โrescueโ the $count uppermost (most significant) words โ instead, these words are lost forever. ๐
If you donโt want this to happen, you have to increase the size of the given bit vector EXPLICITLY and BEFORE you perform the Insert operation, with a statement such as the following:
$vector->Resize($vector->Size() + $count * Bit::Vector->Word_Bits());
Note also that $offset must lie in the permitted range between 0 and "$vector->Word_Size()-1", or a fatal "offset out of range" error will occur. ๐
If $offset + $count exceeds $vector->Word_Size()-1, bestie, then all the words starting at word number $offset through word number $vector->Word_Size()-1 are simply cleared. no cap โจ
$vector->Word_Delete($offset,$count);โ okay so this method deletes, like, actually removes the words starting at position$offsetup to and including word number$offset+$count-1from the internal array of machine words of the given bit vector. itโs giving surgical removal ๐
The remaining uppermost words โ starting at position $offset+$count up to and including word number $vector->Word_Size()-1 โ are moved down by $count places.
The now vacant uppermost (most significant) $count words are then set to zero (cleared).
Important vibe check: this method does NOT decrease the size of the given bit vector. Like, the bit vector is NOT clipped at its upper end to โget rid ofโ the vacant $count uppermost words. <emoji>๐ญ</emoji>
If you donโt want this โ i.e., if you want the bit vector to shrink accordingly โ you have to do so EXPLICITLY and AFTER the Delete operation, with a couple of statements such as these:
$bits = $vector->Size();
$count *= Bit::Vector->Word_Bits();
if ($count > $bits) { $count = $bits; }
$vector->Resize($bits - $count);
Note also that $offset must lie in the permitted range between 0 and $vector->Word_Size()-1, or a fatal offset out of range error will occur. periodt, respect the range ๐จ
If the term $offset + $count exceeds $vector->Word_Size()-1, all the words starting with word number $offset up to word number $vector->Word_Size()-1 are simply cleared.
$vector->Chunk_Store($chunksize,$offset,$chunk);โ this method lets you set more than one bit at a time with different values. main character energy for bulk bit setting ๐ฆ
You can access chunks โ i.e., ranges of contiguous bits โ between one and at most Bit::Vector->Long_Bits() bits wide.
In order to be portable, though, you should never use chunk sizes larger than 32 bits. fr fr, portability matters ๐
If the given $chunksize does not lie between 1 and Bit::Vector->Long_Bits(), a fatal chunk size out of range error will occur.
The method copies the $chunksize least significant bits from the value $chunk to the given bit vector, starting at bit position $offset and proceeding upwards until bit number $offset+$chunksize-1.
(I.e., bit number 0 of $chunk becomes bit number $offset in the given bit vector, and bit number $chunksize-1 becomes bit number $offset+$chunksize-1.) mapping slay โจ
If the term $offset+$chunksize-1 exceeds $vector->Size()-1, the corresponding superfluous (most significant) bits from $chunk are simply ignored.
Note that $offset itself must lie in the permitted range between 0 and $vector->Size()-1, or a fatal offset out of range error will occur.
This method โ as well as the other Chunk_ methods โ is useful, for example, when you are reading in data in chunks of, say, 8 bits, which you need to access later, say, using 16 bits at a time (like audio CD wave files, for instance). iykyk ๐
$chunk = $vector->Chunk_Read($chunksize,$offset);โ this method lets you read the values of more than one bit at a time. reading era ๐
You can read chunks โ i.e., ranges of contiguous bits โ between one and at most Bit::Vector->Long_Bits() bits wide.
In order to be portable, though, you should never use chunk sizes larger than 32 bits.
If the given $chunksize does not lie between 1 and Bit::Vector->Long_Bits(), a fatal chunk size out of range error will occur.
The method returns the $chunksize bits from the given bit vector starting at bit position $offset and proceeding upwards until bit number $offset+$chunksize-1.
(I.e., bit number $offset of the given bit vector becomes bit number 0 of the returned value, and bit number $offset+$chunksize-1 becomes bit number $chunksize-1.) reverse mapping, cute ๐
If the term $offset+$chunksize-1 exceeds $vector->Size()-1, the non-existent bits are simply not returned.
Note that $offset itself must lie in the permitted range between 0 and $vector->Size()-1, or a fatal offset out of range error will occur.
$vector->Chunk_List_Store($chunksize,@chunks);โ this method lets you fill the given bit vector with a list of data packets (โchunksโ) of any size ($chunksize) you like (within certain limits). bulk import but make it cute ๐
In fact the given $chunksize must lie in the range between 1 and Bit::Vector->Long_Bits(), or a fatal chunk size out of range error will occur.
In order to be portable, though, you should never use chunk sizes larger than 32 bits.
The given bit vector is thereby filled in ascending order: The first chunk from the list (i.e., $chunks[0]) fills the $chunksize least significant bits, the next chunk from the list ($chunks[1]) fills the bits number $chunksize to number 2*$chunksize-1, the third chunk ($chunks[2]) fills the bits number 2*$chunksize, to number 3*$chunksize-1, and so on.
If there are fewer chunks in the list than are needed to fill the entire bit vector, the remaining (most significant) bits are cleared, i.e., the previous contents of the given bit vector are always erased completely. clean slate energy โจ
If there are more chunks in the list than are needed to fill the entire bit vector, and/or if a chunk extends beyond $vector->Size()-1 (which happens whenever $vector->Size() is not a multiple of $chunksize), the superfluous chunks and/or bits are simply ignored.
The method is useful, for example (and among many other applications), for the conversion of packet sizes in a data stream.
This method can also be used to store an octal string in a given bit vector:
$vector->Chunk_List_Store(3, split(//, reverse $string));
Note however that unlike the conversion methods from_Hex(), from_Bin(), from_Dec() and from_Enum(), this statement does not include any syntax checking, i.e., it may fail silently, without warning. not the silent fail ๐
To perform syntax checking, add the following statements:
if ($string =~ /^[0-7]+$/)
{
# okay, go ahead with conversion as shown above
}
else
{
# error, string contains other than octal characters
}
Another application is to store a repetitive pattern in a given bit vector:
$pattern = 0xDEADBEEF;
$length = 32; # = length of $pattern in bits
$size = $vector->Size();
$factor = int($size / $length);
if ($size % $length) { $factor++; }
$vector->Chunk_List_Store($length, ($pattern) x $factor);
@chunks = $vector->Chunk_List_Read($chunksize);โ this method lets you access the contents of the given bit vector in form of a list of data packets (โchunksโ) of a size ($chunksize) of your choosing (within certain limits). export era ๐ง
In fact the given $chunksize must lie in the range between 1 and Bit::Vector->Long_Bits(), or a fatal chunk size out of range error will occur.
In order to be portable, though, you should never use chunk sizes larger than 32 bits.
The given bit vector is thereby read in ascending order: The $chunksize least significant bits (bits number 0 to $chunksize-1) become the first chunk in the returned list (i.e., $chunks[0]). The bits number $chunksize to 2*$chunksize-1 become the next chunk in the list ($chunks[1]), and so on.
If $vector->Size() is not a multiple of $chunksize, the last chunk in the list will contain fewer bits than $chunksize.
BEWARE that for large bit vectors and/or small values of $chunksize, the number of returned list elements can be extremely large! BE CAREFUL! ๐ญ
You could blow up your application with lack of memory (each list element is a full-grown Perl scalar, internally, with an associated memory overhead for its administration!) or at least cause a noticeable, more or less long-lasting โfreezeโ of your application! not the freeze ๐
Possible applications:
The method is especially useful in the conversion of packet sizes in a data stream.
This method can also be used to convert a given bit vector to a string of octal numbers:
$string = reverse join('', $vector->Chunk_List_Read(3));
$vector->Index_List_Remove(@indices);โ this method lets you specify a list of indices of bits which should be turned off in the given bit vector. turning bits off, bye bestie ๐
In fact this method is a shortcut for
foreach $index (@indices)
{
$vector->Bit_Off($index);
}
In contrast to all other import methods in this module, this method does NOT clear the given bit vector before processing its list of arguments.
Instead, this method allows you to accumulate the results of various consecutive calls. stacking calls, iconic โจ
(The same holds for the method Index_List_Store(). As a consequence, you can โwipe outโ what you did using the method Index_List_Remove() by passing the identical argument list to the method Index_List_Store().)
$vector->Index_List_Store(@indices);โ this method lets you specify a list of indices of bits which should be turned on in the given bit vector. bits on, slay ๐ฅ
In fact this method is a shortcut for
foreach $index (@indices)
{
$vector->Bit_On($index);
}
In contrast to all other import methods in this module, this method does NOT clear the given bit vector before processing its list of arguments.
Instead, this method allows you to accumulate the results of various consecutive calls.
(The same holds for the method Index_List_Remove(). As a consequence, you can โwipe outโ what you did using the method Index_List_Store() by passing the identical argument list to the method Index_List_Remove().)
@indices = $vector->Index_List_Read();โ this method returns a list of Perl scalars. scalar collection moment ๐
The list contains one scalar for each set bit in the given bit vector.
BEWARE that for large bit vectors, this can result in a literally overwhelming number of list elements! BE CAREFUL! You could run out of memory or slow down your application considerably! ๐ญ
Each scalar contains the number of the index corresponding to the bit in question.
These indices are always returned in ascending order.
If the given bit vector is empty (contains only cleared bits) or if it has a length of zero (if it contains no bits at all), the method returns an empty list.
This method can be useful, for instance, to obtain a list of prime numbers:
$limit = 1000; # or whatever
$vector = Bit::Vector->new($limit+1);
$vector->Primes();
@primes = $vector->Index_List_Read();
$vec3->Or($vec1,$vec2);
$set3->Union($set1,$set2);
Okay so this one does the union of $set1 and $set2 and drops the result into $set3 ๐
In set theory bestie land this is written as "$set3 = $set1 u $set2" (and that u is the "cup" operator, iykyk).
(On systems where the "cup" character just isn't available, people usually write it with a plus sign + instead โ no drama ๐ซถ)
You can totally do in-place calculations too, meaning $set3 can be literally the same thing as $set1 or $set2 or even both. Slay.
$vec3->And($vec1,$vec2);
$set3->Intersection($set1,$set2);
This one computes the intersection of $set1 and $set2, result goes in $set3 โจ
Set-theory notation: "$set3 = $set1 n $set2" (the n is the "cap" operator).
(If your system doesn't have the "cap" character, the convention is an asterisk * instead ๐
)
In-place calculation is also possible here โ $set3 may be identical with $set1 or $set2 or both.
$vec3->AndNot($vec1,$vec2);
$set3->Difference($set1,$set2);
This one is the difference: $set1 less $set2, stored in $set3 ๐ฆ
Normally written "$set3 = $set1 \ $set2" in set theory (where \ is the "less" operator).
In-place calculation? Also possible. $set3 may be identical with $set1 or $set2 or both. Go off.
$vec3->Xor($vec1,$vec2);
$set3->ExclusiveOr($set1,$set2);
This calculates the symmetric difference of $set1 and $set2 and stores it in $set3 ๐
You can write it as "$set3 = ($set1 u $set2) \ ($set1 n $set2)" in set theory โ that's the union of the two sets minus their intersection, periodt.
When sets are implemented as bit vectors, that formula is exactly equivalent to the exclusive-or between the corresponding bits of the two bit vectors (which is literally where the name of this method comes from ๐).
Also note: this method is way more efficient than evaluating that formula explicitly, because internally it uses a built-in machine language instruction. Not me being impressed ๐ญ
In-place calculation is possible, yes โ $set3 may be identical with $set1 or $set2 or both.
$vec2->Not($vec1);
$set2->Complement($set1);
This one calculates the complement of $set1 and stores it in $set2 ๐
In "big integer" arithmetic, this is the same thing as calculating the one's complement of the number stored in the bit vector $set1 in binary representation.
In-place calculation is also possible here โ $set2 may be identical with $set1.
if ($set1->subset($set2))
Returns "true" (1) if $set1 is a subset of $set2 (like, completely contained in it), and "false" (0) otherwise โญ
What that means: every bit that's set (1) in $set1 must also be set in $set2, but $set2 is allowed to have set bits that $set1 doesn't have โ that's still a valid subset relationship between the two, bestie.
And note, by definition, if two sets are identical they're also subsets (and also supersets) of each other. Iconic mutual behaviour ๐
$norm = $set->Norm();
Returns the norm (the number of bits that are set) of the given vector.
Which is equivalent to the number of elements contained in the given set โจ
This uses a byte lookup table to count the set bits per byte, so the time it needs (and the number of loops) is linearly proportional to the length of the given bit vector, in bytes.
On average this should be the fastest algorithm. Ngl, it's giving efficiency.
$norm = $set->Norm2();
Returns the norm (number of set bits) of the given vector.
Equivalent to the number of elements contained in the given set.
Does the same thing as Norm() above, just with a different algorithm:
This one counts set bits and cleared bits at the same time, and stops as soon as either one runs out โ so it needs at most half as many loops per machine word as the total number of bits in a machine word. In fact, it needs a number of loops equal to the minimum of the number of set bits and the number of cleared bits ๐ง
This might be faster than Norm() on some systems, depending on the system's architecture and the compiler and optimisation used. It's a vibe for bit vectors with sparse set bits, and for bit vectors with sparse cleared bits (i.e., ones that are mostly set bits).
$norm = $set->Norm3();
Returns the norm (number of set bits) of the given vector.
Equivalent to the number of elements contained in the given set.
Same job as Norm() and Norm2() above, different algorithm again.
In fact, this is the implementation of Norm() that previous versions of this module used ๐
It needs a number of loops per machine word equal to the number of set bits in that machine word.
So it's only fast for bit vectors with sparse set bits โ and even then, whether it beats the two methods above depends on the system's architecture and compiler.
On average though? Probably the slowest of the three. F in the chat ๐
$min = $set->Min();
Returns the minimum of the given set, i.e., the minimum of all indices of all set bits in the bit vector $set ๐
If the set is empty (no set bits at all), plus infinity is returned โ represented by the constant MAX_LONG on your system.
(That constant is usually 2 ^ (n-1) - 1, where "n" is the number of bits of an unsigned long on your machine.)
$max = $set->Max();
Returns the maximum of the given set, i.e., the maximum of all indices of all set bits in the bit vector $set ๐ฆ
If the set is empty (no set bits), minus infinity is returned โ represented by the constant MIN_LONG on your system.
(That constant is usually -(2 ^ (n-1) - 1) or -(2 ^ (n-1)), where "n" is the number of bits of an unsigned long on your machine.)
$m3->Multiplication($r3,$c3,$m1,$r1,$c1,$m2,$r2,$c2);
This multiplies two boolean matrices (stored as bit vectors) $m1 and $m2, and stores the result in matrix $m3 ๐ฅ
It uses the binary xor operation ("^") as the boolean addition operator ("+").
An exception gets raised if the product of the number of rows and columns of any of the three matrices differs from the actual size of their underlying bit vector ๐ญ
An exception also gets raised if the numbers of rows and columns of the three matrices don't harmonize the required way:
rows3 == rows1
cols3 == cols2
cols1 == rows2
This method is used by the module Math::MatrixBool.
See Math::MatrixBool(3) for the details.
$m3->Product($r3,$c3,$m1,$r1,$c1,$m2,$r2,$c2);
Also multiplies two boolean matrices (stored as bit vectors) $m1 and $m2, result in $m3 โจ
This special method uses the binary or operation ("|") as the boolean addition operator ("+").
An exception is raised if the product of the number of rows and columns of any of the three matrices differs from the actual size of their underlying bit vector.
An exception is also raised if the numbers of rows and columns of the three matrices don't harmonize like this:
rows3 == rows1
cols3 == cols2
cols1 == rows2
This method is used by the module Math::MatrixBool.
See Math::MatrixBool(3) for the details.
$matrix->Closure($rows,$cols);
This one calculates the reflexive transitive closure of the given boolean matrix (stored as a bit vector) using Kleene's algoritm ๐ง
(See Math::Kleene(3) for a brief intro to the theory behind Kleene's algorithm.)
The reflexive transitive closure answers the question of whether a path exists between any two vertices of a graph whose edges are given as a matrix:
If a (directed) edge exists going from vertex i to vertex j, then the element in the matrix with coordinates (i,j) is set to 1 (otherwise it stays at 0).
If the edges are undirected, the resulting matrix is symmetric โ elements (i,j) and (j,i) always contain the same value ๐
So the matrix representing the graph's edges only tells you whether an EDGE exists between any two vertices, but the reflexive transitive closure tells you whether a PATH (a series of adjacent edges) exists between them! That's the glow-up โจ
โ ๏ธ Heads up bestie: the contents of the given matrix are modified by this method. Make a copy of the initial matrix in time if you're gonna need it again later. No cap.
An exception is raised if the given matrix isn't quadratic, i.e., if the number of rows and columns of the given matrix isn't identical.
An exception is also raised if the product of the number of rows and columns of the given matrix differs from the actual size of its underlying bit vector.
This method is used by the module Math::MatrixBool.
See Math::MatrixBool(3) for the details.
$matrix2->Transpose($rows2,$cols2,$matrix1,$rows1,$cols1);
Calculates the transpose of a boolean matrix $matrix1 (stored as a bit vector) and stores the result in matrix $matrix2 ๐ฆ
The transpose of a boolean matrix representing the edges of a graph can be used for finding the strongly connected components of that graph. Obsessed tbh.
An exception is raised if the product of the number of rows and columns of either of the two matrices differs from the actual size of its underlying bit vector.
An exception is also raised if these conditions aren't met:
rows2 == cols1
cols2 == rows1
๐ Careful: in-place processing ($matrix1and$matrix2are identical) is only possible if the matrix is quadratic. Otherwise you get a fatalmatrix is not quadraticerror. You've been warned.
This method is used by the module Math::MatrixBool.
See Math::MatrixBool(3) for the details.
๐ SEE ALSO ๐
Bit::Vector::Overload(3), Bit::Vector::String(3), Storable(3).
Set::IntRange(3), Math::MatrixBool(3), Math::MatrixReal(3), DFA::Kleene(3), Math::Kleene(3), Graph::Kruskal(3).
โญ VERSION โญ
This man page documents Bit::Vector version 7.4.
๐ AUTHOR ๐
Steffen Beyer
mailto:STBEY@cpan.org
http://www.engelschall.com/u/sb/download/
๐ COPYRIGHT ๐
Copyright (c) 1995 - 2013 by Steffen Beyer. All rights reserved.
๐ LICENSE ๐
Okay bestie, legal era โ but it's actually good news, promise ๐ซถ
This package is free software; you can redistribute it and/or modify it under the same terms as Perl itself, i.e., under the terms of the "Artistic License" or the "GNU General Public License".
And the C library at the core of this Perl module can additionally be redistributed and/or modified under the terms of the "GNU Library General Public License". Yes, you read that right โ extra permission, no cap ๐
Please refer to the files "Artistic.txt", "GNU_GPL.txt" and "GNU_LGPL.txt" in this distribution for details! They're literally right there in the distribution, go look ๐ธ
โจ DISCLAIMER โจ
This package is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ๐ญ
Like, it's giving "we hope this slays for you" but fr fr no promises โ the legal girlies made sure of that ๐
See the "GNU General Public License" for more details.
And that's the whole page, bestie โ you made it to the end, icon behavior honestly ๐ This one's from perl v5.42.0, dated 2025-02-06, filed under Vector(3) โ so yeah, the Vector manual page, version 5.42.0, February 6th 2025, signed, sealed, slayed ๐
โจ๐ฆ
๐ฆ where this page comes from
- opensuse-leap 16.0: perl-Bit-Vector 7.400.0-160000.2.2 ยท Artistic-1.0 OR GPL-1.0-or-later
- opensuse-leap 16.0: perl-Bit-Vector 7.400.0-160000.2.2 ยท Artistic-1.0 OR GPL-1.0-or-later
- opensuse-leap 16.0: perl-Bit-Vector 7.400.0-160000.2.2 ยท Artistic-1.0 OR GPL-1.0-or-later
- opensuse-leap 16.0: perl-Bit-Vector 7.400.0-160000.2.2 ยท Artistic-1.0 OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms