During a calculation, i'm facing a problem on bitwise Left Operator on PHP and JS.
On a certain level/range both php and JS is giving the same output.
For Example: 1<<30 = 1073741824 (Both PHP and JS are right.)
But the problem occurs when i'm trying to move 40.
1<<40;
// php: 1099511627776
// JS: 256
After having study on it , i came to a point that JS can't (or and) can calculate only 32 bit number on bitwise operand.
If there is any procedure, please help. Thanks in advance.
Update: PHP the below function I'm using for convert byte to max possible unit, and was trying to port it into javascript for using inside browser and nodejs.
function formatBytes( $bytes, $args = [] ): array {
if ( is_string( $args ) ) {
$args = [ 'flag' => $args ];
}
$args = array_merge( [
'flag' => 'Bytes',
'forStorage' => true,
], $args );
$units = array( 'Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' );
$unit = $args['forStorage'] ? 1024 : 1000;
if ( 'Bytes' !== $args['flag'] && in_array( $args['flag'], $units, true ) ) {
$key = array_search( $args['flag'], $units );
$units = array_slice( $units, $key );
}
$bytes = max( $bytes, 0 );
$pow = floor( ( $bytes ? log( $bytes ) : 0 ) / log( $unit ) );
$pow = min( $pow, count( $units ) - 1 );
$bytes /= ( 1 << ( 10 * $pow ) );
return [
'value' => $bytes,
'unit' => $units[ $pow ],
];
}
JavaScript Version
function formatBytes(bytes, args = {}) {
const defaults = {
'flag': 'Bytes',
'forStorage': true,
};
args = {...defaults, ...args};
let units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const unit = args.forStorage ? 1024 : 1000;
if ('Bytes' !== args.flag && units.includes(args.flag)) {
const key = units.indexOf(args.flag);
units = units.slice(key, units.length);
}
bytes = Math.max(bytes, 0);
let pow = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(unit));
pow = Math.min(pow, units.length - 1);
bytes /= (1 << (10 * pow));
return {
value: bytes,
unit: units[pow]
};
}
This works perfectly but until certain limit.
E.G.
// PHP
print_r( formatBytes( 3114766203813 ) );
// output: Array ( [value] => 2.8328633596293 [unit] => TB )
// JS
console.log( formatBytes(3114766203813) );
// output: {value: 12167055483.644531, unit: 'TB'}
PS: I have modified the JS function to resolve the issue, but curious to learn why this (in the above version of my code) happening and how can i resolve the issue.