perlfunc
gods
<P>
vec - test or set particular bits in a string
<P>
<HR>
<P>
vec
<FONT SIZE=-1>EXPR,OFFSET,BITS</FONT>
<P>
<HR>
<P>
Treats the string in
<FONT SIZE=-1>EXPR</FONT> as a vector of unsigned integers, and returns the value of the bit field specified by
<FONT SIZE=-1>OFFSET.</FONT>
<FONT SIZE=-1>BITS</FONT> specifies the number of bits that are reserved for each entry in the bit vector. This must be a power of two from 1 to 32.
[perlfunc:vec|vec()] may also be assigned to, in which case parentheses are needed to give the
expression the correct precedence as in
<P>
<PRE> vec($image, $max_x * $x + $y, 8) = 3;
</PRE>
<P>
Vectors created with [perlfunc:vec|vec()] can also be manipulated with the logical operators <CODE>|</CODE>, <CODE>&amp;</CODE>, and <CODE>^</CODE>, which will assume a bit vector operation is desired when both operands
are strings.
<P>
The following code will build up an
<FONT SIZE=-1>ASCII</FONT> string saying <CODE>'PerlPerlPerl'</CODE>. The comments show the string after each step. Note that this code works
in the same way on big-endian or little-endian machines.
<P>
<PRE> my $foo = '';
vec($foo, 0, 32) = 0x5065726C; # 'Perl'
vec($foo, 2, 16) = 0x5065; # 'PerlPe'
vec($foo, 3, 16) = 0x726C; # 'PerlPerl'
vec($foo, 8, 8) = 0x50; # 'PerlPerlP'
vec($foo, 9, 8) = 0x65; # 'PerlPerlPe'
vec($foo, 20, 4) = 2; # 'PerlPerlPe' . &quot;\x02&quot;
vec($foo, 21, 4) = 7; # 'PerlPerlPer'
# 'r' is &quot;\x72&quot;
vec($foo, 45, 2) = 3; # 'PerlPerlPer' . &quot;\x0c&quot;
vec($foo, 93, 1) = 1; # 'PerlPerlPer' . &quot;\x2c&quot;
vec($foo, 94, 1) = 1; # 'PerlPerlPerl'
# 'l' is &quot;\x6c&quot;
</PRE>
<P>
To transform a bit vector into a string or array of 0's and 1's, use these:
<P>
<PRE> $bits = unpack(&quot;b*&quot;, $vector);
@bits = split(//, unpack(&quot;b*&quot;, $vector));
</PRE>
<P>
If you know the exact length in bits, it can be used in place of the <CODE>*</CODE>.
<HR>