NAME

vec - test or set particular bits in a string


SYNOPSIS

vec EXPR,OFFSET,BITS


DESCRIPTION

Treats the string in EXPR as a vector of unsigned integers, and returns the value of the bit field specified by OFFSET. BITS 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. vec() may also be assigned to, in which case parentheses are needed to give the expression the correct precedence as in

    vec($image, $max_x * $x + $y, 8) = 3;

Vectors created with vec() can also be manipulated with the logical operators |, &, and ^, which will assume a bit vector operation is desired when both operands are strings.

The following code will build up an ASCII string saying 'PerlPerlPerl'. The comments show the string after each step. Note that this code works in the same way on big-endian or little-endian machines.

    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'   . "\x02"
    vec($foo, 21,  4) = 7;              # 'PerlPerlPer'
                                        # 'r' is "\x72"
    vec($foo, 45,  2) = 3;              # 'PerlPerlPer'  . "\x0c"
    vec($foo, 93,  1) = 1;              # 'PerlPerlPer'  . "\x2c"
    vec($foo, 94,  1) = 1;              # 'PerlPerlPerl'
                                        # 'l' is "\x6c"

To transform a bit vector into a string or array of 0's and 1's, use these:

    $bits = unpack("b*", $vector);
    @bits = split(//, unpack("b*", $vector));

If you know the exact length in bits, it can be used in place of the *.


DISCLAIMER

We are painfully aware that these documents may contain incorrect links and misformatted HTML. Such bugs lie in the automatic translation process that automatically created the hundreds and hundreds of separate documents that you find here. Please do not report link or formatting bugs, because we cannot fix per-document problems. The only bug reports that will help us are those that supply working patches to the installhtml or pod2html programs, or to the Pod::HTML module itself, for which I and the entire Perl community will shower you with thanks and praises.

If rather than formatting bugs, you encounter substantive content errors in these documents, such as mistakes in the explanations or code, please use the perlbug utility included with the Perl distribution.

--Tom Christiansen, Perl Documentation Compiler and Editor


Return to the Perl Documentation Index.
Return to the Perl Home Page.