Skip to content

Instantly share code, notes, and snippets.

@colomon
Forked from pmichaud/gist:5678418
Last active December 17, 2015 21:59
Show Gist options
  • Save colomon/5678473 to your computer and use it in GitHub Desktop.
Save colomon/5678473 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;
}
for (-1, -2, -3, -4) -> $n { say $n => msb($n); }
for (-126, -127, -128, -129) -> $n { say $n => msb($n); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment