Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unfamiliar characters used in JavaScript encryption script

Here is an excerpt from a JS encryption script that I am studying.

function permutationGenerator(nNumElements) {
    this.nNumElements     = nNumElements;
    this.antranspositions = new Array;
    var k = 0;
    for (i = 0; i < nNumElements - 1; i++)
    for (j = i + 1; j < nNumElements; j++)
    this.antranspositions[ k++ ] = ( i << 8 ) | j;
    // keep two positions as lo and hi byte!
    this.nNumtranspositions = k;
    this.fromCycle = permutationGenerator_fromCycle;
}

Can anyone explain the use of the double less than signs <<, as well as the single pipe | ?

Later in the script double greater than signs occur as well >>, also single ampersand & .

function permutationGenerator_fromCycle(anCycle) {
    var anpermutation = new Array(this.nNumElements);
    for (var i = 0; i < this.nNumElements; i++) anpermutation[i] = i;
    for (var i = 0; i < anCycle.length; i++) {
        var nT = this.antranspositions[anCycle[i]];
        var n1 = nT & 255;
        var n2 = (nT >> 8) & 255; // JC
        nT = anpermutation[n1];
        anpermutation[n1] = anpermutation[n2];
        anpermutation[n2] = nT;
    }
    return anpermutation;
}

I am familiar with single < or > and of course logical && and logical || .

Thoughts?

like image 525
jerome Avatar asked Dec 01 '09 19:12

jerome


3 Answers

Left shift 8 bits and bitwise OR with j.

<< is the left shift operator. Shifts the bits in the variable left the number of positions indicated.

>> is the right shift operator. Shifts the bits in the variable right the number of position indicated.

| is the bitwise OR operator. Performs a logical OR on each bit in the two operands.

& is the bitwise AND operator. Performs a logical AND on each bit in the two operands.

like image 189
tvanfosson Avatar answered Oct 14 '22 08:10

tvanfosson


<< is a bitwise left shift. >> is a bitwise right shift. | is a bitwise OR. & is a bitwise AND. Please see this reference for more information.

like image 8
Ron's Brain Avatar answered Oct 14 '22 07:10

Ron's Brain


| = bitwise or

1010
0100
----
1110

& = bitwise and

1011
0110
----
0010

so it's the same as && and || just with the single bits

<< is left shift, so

0110 << 2 shifts the numbers left by two positions, yielding 011000 another way to think of this is multiplication by two, so x<<1 == x*2, x<<2 == x*2*2 and so on, so it's x * Math.pow(2,n) for x<

>> 

is the opposite, so 0110 >> 2 ---> 0001 you can think of it as division by two, BUT with rounding down, so it equals

Math.floor(x/Math.pow(2,n)) 
like image 13
Zenon Avatar answered Oct 14 '22 08:10

Zenon