Core Function BitSHIFT

From Sputnik Wiki
Jump to: navigation, search
BitShift ( <value>, <shift> )

Contents

Description

Performs a bit shifting operation.

Parameters

value

The number to be shifted.

shift

Number of bits to shift to the right (negative numbers shift left).

Return Value

Returns the value shifted by the required number of bits.

Bit operations are performed as 32-bit integers (INT32).

Remarks

Remember hex notation can be used for numbers.

Right shifts are equivalent to halving; left shifts to doubling.

Some might wonder the point of such a function when clear << and >> operators exist but why not!.

Example

$x = BitShift(14, 2);
println( "Value is: $x" );
// x == 3 because 1110b right-shifted twice is 11b == 3
 
$y = BitShift(14, -2);
println( "Value is: $y" );
// y == 56 because 1110b left-shifted twice is 111000b == 56
 
$z = BitShift( 1, -31);
println( "Value is: $z" );
// z == -2147483648 because in 2's-complement notation, the
// 32nd digit from the right has a negative sign.

Same thing but this time using the << and >> operators

$x = 14 >> 2;
println( "Value is: $x" );
// x == 3 because 1110b right-shifted twice is 11b == 3
 
$y = 14 << 2;
println( "Value is: $y" );
// y == 56 because 1110b left-shifted twice is 111000b == 56
 
$z =  1 << 31;
println( "Value is: $z" );
// z == -2147483648 because in 2's-complement notation, the
// 32nd digit from the right has a negative sign.

Heres an interesting way to break an INT32 down into bytes using bitwise shift :

$value = 1337;
$Array[0] = (byte)($value);
$Array[1] = (byte)($value >> 8);
$Array[2] = (byte)($value >> 16);
$Array[3] = (byte)($value >> 23);
 
Foreach ($value as $_)
{
	println("Value is '$_'");
}
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox