首页 > 解决方案 > Perl <<= and ^= Meaning

问题描述

Hello I´m trying to convert a bunch of Perl scripts to C#. A have this piece of code and I don´t know what <<=, ^=, &= means. Can someone please tell me the meaning of the part (???) too?. Thanks in advance.

$cwl = 6;
$sr = 1;
    for ($i=0; $i<$gf::field; $i++) {
        $gf::log[$sr] = $i;
        $gf::alog[$i] = $sr;
        $sr <<= 1;
        if ($sr & (1<<$cwl)) {$sr ^= $prim} (???)
        $sr &= $gf::field;
    }

标签: perl

解决方案


These are:

  • <<= = Left shift equal operator, shifts the source variable's bits by n places to the left and assign back to source variable.
  • ^= = Bitwise XOR equal operator. XORs the source variable by the right hand variable, and assigns to the source variable.
  • &= = Bitwise AND equal operator. ANDs the source variable and the right hand variable, and assigns the result to the source variable.

The C# equivalents from your code above:

Left Shift

# Perl code
$sr <<= 1;

// C# code
sr = sr << 1;

Bitwise XOR

# Perl code
$sr ^= $prim

// C# code
sr = sr ^ prim

Bitwise AND

# Perl code
$sr &= $gf::field

// C# code
sr = sr & gf.field // or whatever you've named $gf::field

Edit following OP comment

OP asked whether:

if ($sr & (1<<$cwl))

Can be translated to:

cwl=1 << cwl;
if (Convert.ToBoolean(sr) & Convert.ToBoolean(cwl))

I think you've made an error here. cwl is not reassigned in the original if statement in Perl.

In fact, the logic of the operation is to say:

  • Is sr bitwise AND 1 left-shifted by cwl true?

I'd be tempted to rewrite the Perl code to:

if ((sr & (1 << cwl)) != 0)

Why? The original statement ascertains whether the result of the if statement is true. Any non-zero value in Perl is true, therefore we need to perform the operation as per the Perl and test for a non-zero value.


推荐阅读