Skip to content

Commit

Permalink
- Simplified the following Number methods: as_oct, as_bin, as_hex
Browse files Browse the repository at this point in the history
Example:
	say 10.as_oct;   # prints: "12"
	say 127.as_hex;  # prints: "7f"
	say 10.as_bin;   # prints "1010"

No leading symbol is added.
  • Loading branch information
trizen committed Aug 9, 2015
1 parent 1c56099 commit 148ecef
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 7 deletions.
6 changes: 3 additions & 3 deletions lib/Sidef/Types/Number/Number.pm
Original file line number Diff line number Diff line change
Expand Up @@ -547,23 +547,23 @@ package Sidef::Types::Number::Number {
sub to_bin {
my ($self) = @_;
state $x = require Math::BigInt;
Sidef::Types::String::String->new(Math::BigInt->new($self->get_value)->as_bin);
Sidef::Types::String::String->new(substr(Math::BigInt->new($self->get_value)->as_bin, 2));
}

*as_bin = \&to_bin;

sub to_oct {
my ($self) = @_;
state $x = require Math::BigInt;
Sidef::Types::String::String->new(Math::BigInt->new($self->get_value)->as_oct);
Sidef::Types::String::String->new(substr(Math::BigInt->new($self->get_value)->as_oct, 1));
}

*as_oct = \&to_oct;

sub to_hex {
my ($self) = @_;
state $x = require Math::BigInt;
Sidef::Types::String::String->new(Math::BigInt->new($self->get_value)->as_hex);
Sidef::Types::String::String->new(substr(Math::BigInt->new($self->get_value)->as_hex, 2));
}

*as_hex = \&to_hex;
Expand Down
4 changes: 3 additions & 1 deletion lib/Sidef/Types/Number/NumberFast.pm
Original file line number Diff line number Diff line change
Expand Up @@ -297,9 +297,11 @@ package Sidef::Types::Number::Number {
$reminder = ($dec >>= 1) % 2;
}
Sidef::Types::String::String->new("0b" . join('', @bin));
Sidef::Types::String::String->new(join('', @bin));
}
*as_bin = \&to_bin;
sub commify {
my ($self) = @_;
Expand Down
2 changes: 1 addition & 1 deletion scripts/Rosettacode/Binary_digits.sf
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
#

[5, 50, 9000].each { |n|
say n.to_bin.substr(2);
say n.as_bin;
}
4 changes: 2 additions & 2 deletions scripts/declare_primitive_type.sf
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ say b; # => 6
b.is_a(MyInt) || die "error!";
MyInt.is_a(a) || die "error!";

say a.to_hex; # => "0x9" -- an hexadecimal string
say a.to_hex; # => "9" -- an hexadecimal string

a.to_hex == "0x9" || die "error!";
a.to_hex == "9" || die "error!";
b == 6 || die "error!";
a == MyInt(9) || die "error!";
a == 9 || die "error!";
Expand Down

0 comments on commit 148ecef

Please sign in to comment.