11 Feb

perl: rounding KiB values to MiB boundaries

When you have to deal with kilobyte or kibibyte values in today’s real-world computers, you often want extremely similar values to evaluate to „equal“. An easy solution is to round them to full Mebibytes. This can be easily done in every programming language which supports integer division and the modulo operator.

For example in Perl:

sub _rnd_kbval_to_mib_borders {
      my $input  = shift;
      my $base   = $input DIV 1024;
      my $modulo = $input % 1024;
      return ( $modulo < 512 ) ? $base * 1024 : ( $base + 1 ) * 1024;

This approach is trivial but can safe you a lot of headache.

Perl Newbie sagt:

Valuable information. Lucky me I found your website by accident, and I’m shocked why this accident didn’t happened earlier! I bookmarked it. Zauberer