1
0
mirror of https://github.com/danog/phpseclib.git synced 2024-12-12 09:09:39 +01:00

Strings: misc tweaks

This commit is contained in:
terrafrost 2021-12-26 00:40:43 -06:00
parent df918f6af9
commit cc6edd81a6

View File

@ -308,7 +308,7 @@ abstract class Strings
* @param string $x
* @return string
*/
public static function bin2bits($x)
public static function bin2bits($x, $trim = true)
{
/*
// the pure-PHP approach is slower than the GMP approach BUT
@ -337,7 +337,7 @@ abstract class Strings
}
}
return ltrim($bits, '0');
return $trim ? ltrim($bits, '0') : $bits;
}
/**
@ -350,14 +350,21 @@ abstract class Strings
public static function switchEndianness($x)
{
$r = '';
// from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith32Bits
for ($i = strlen($x) - 1; $i >= 0; $i--) {
$b = ord($x[$i]);
$p1 = ($b * 0x0802) & 0x22110;
$p2 = ($b * 0x8020) & 0x88440;
$r.= chr(
(($p1 | $p2) * 0x10101) >> 16
);
if (PHP_INT_SIZE === 8) {
// 3 operations
// from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64BitsDiv
$r.= chr((($b * 0x0202020202) & 0x010884422010) % 1023);
} else {
// 7 operations
// from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith32Bits
$p1 = ($b * 0x0802) & 0x22110;
$p2 = ($b * 0x8020) & 0x88440;
$r.= chr(
(($p1 | $p2) * 0x10101) >> 16
);
}
}
return $r;
}