Skip to content

Instantly share code, notes, and snippets.

@pmichaud
Created May 30, 2013 14:46
Show Gist options
  • Save pmichaud/5678418 to your computer and use it in GitHub Desktop.
Save pmichaud/5678418 to your computer and use it in GitHub Desktop.
sub msb(Int $self) {
return Nil if $self == 0;
return 0 if $self == -1;
my $msb = 0;
my $x = $self;
$x = ($x + 1) * -2 if $x < 0; # handle negative conversions
while $x > 0xff { $msb += 8; $x +>= 8; }
if $x > 0x0f { $msb += 4; $x +>= 4; }
if $x +& 0x8 { $msb += 3; }
elsif $x +& 0x4 { $msb += 2; }
elsif $x +& 0x2 { $msb += 1; }
$msb;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment