Skip to content

Instantly share code, notes, and snippets.

@renaatdemuynck
Created February 4, 2015 13:33
Show Gist options
  • Save renaatdemuynck/b68acb662ba289c95d76 to your computer and use it in GitHub Desktop.
Save renaatdemuynck/b68acb662ba289c95d76 to your computer and use it in GitHub Desktop.
CREATE FUNCTION `format_filesize`(filesize INTEGER) RETURNS varchar(20) CHARSET utf8
BEGIN
DECLARE log INT;
SET log = TRUNCATE(LOG(1024, filesize), 0);
RETURN CONCAT(ROUND(filesize / POW(1024, log), 2), ' ',
ELT(log + 1, 'Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB', 'BB'));
END
CREATE FUNCTION `parse_filesize`(filesize varchar(50) CHARSET utf8) RETURNS int(11)
BEGIN
DECLARE val, exp INT;
DECLARE unit VARCHAR(10);
SET val = CAST(filesize AS UNSIGNED);
SET unit = TRIM(SUBSTRING(filesize, LENGTH(val) + 1));
SET exp = FIELD(unit, 'Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB', 'BB') - 1;
RETURN POW(1024, exp) * val;
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment