edoceo

Below are two functions in PHP to assist with calculating bandwidth information. The first to_bytes($value,$unit) will turn value into bytes based on what the unit is. The function bytes_to($value, $unit) converts the $value of bytes to the specified unit. This is what drives our Bandwidth Calculator.

Parameters

The two functions both use the $unit parameter the same. The supported units are:

b  = bits        B  = Bytes
Kb = Kilobits    KB = Kilobytes
Mb = Megabits    MB = Megabytes
Gb = Gigabits    GB = Gigabytes

Function Definitions

$k = 1024;
$m = 1048576;
$g = 1073741824;

function to_bytes($value, $unit)
{
  global $k, $m, $g;
  switch (trim($unit))
  {
    case "b": //bytes
      return ($value / 8);
    case "Kb": //Kilobits
      return (($value * $k) / 8);
    case "Mb": // Megabits
      return (($value * $m) / 8);
    case "Gb": // Gigabits
      return (($value * $g) / 8);
    case "B": // Bytes
      return $value;
    case "KB": // Kilobytes
      return ($value * $k);
    case "MB": // Megabytes
      return ($value * $m);
    case "GB": // Gigabytes
      return ($value * $g);
    default: return 0;
  }
}

function bytes_to($value, $unit)
{
  global $k, $m, $g;
  switch (trim($unit))
  {
    case "b": //bytes
      return ($value * 8);
    case "Kb": //Kilobits
      return (($value * 8) / $k);
    case "Mb": // Megabits
      return (($value * 8) / $m);
    case "Gb": // Gigabits
      return (($value * 8) / $g);
    case "B": // Bytes
      return $value;
    case "KB": // Kilobytes
      return ($value / $k);
      //return bcdiv($value, $k, 4);
    case "MB": // Megabytes
      return ($value / $m);
    case "GB": // Gigabytes
      return ($value / $g);
    default: return 0;
  }
}

Loading Comments from Disqus...