Skip to content

Commit

Permalink
Integer.to_string()
Browse files Browse the repository at this point in the history
  • Loading branch information
msipos committed Jun 7, 2011
1 parent bf8ee69 commit 75c44db
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
42 changes: 38 additions & 4 deletions modules/Integer/Integer.rip
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,41 @@ class Integer
sprintf(buf, "%"PRId64, unpack_int64(__self)); $
return $ string_to_val(buf) $

to_string(Integer base, Integer pad_width)
out = nil
switch base
case 10
out = self.to_s()
case 2
$ char buf[70];
char* s = buf;
uint64 self = (uint64) unpack_int64(__self);
uint64 fl = ((uint64) 1) << 61;

bool started = false;
while (fl != 0){
if (fl & self) {
*s = '1';
s++;
started = true;
} else {
if (started) {
*s = '0';
s++;
}
}
fl = fl >> 1;
}
*s = 0; $
out = $ string_to_val(buf) $
else
raise Error.new("Invalid base")
loop
if out.size < pad_width
out = "0" + out
else
return out

#$ rdoc-name Integer.odd?
#$ rdoc-header Integer.odd?()
#$ Returns true if Integer is odd.
Expand Down Expand Up @@ -94,7 +129,7 @@ class Integer
self = self & (~mask);
self = self | ((unpack_int64(__i) << loc) & mask); $
return $ pack_int64(self) $

get_bit(Integer loc)
$ int64 loc = unpack_int64(__loc);
if (loc < 1 or loc > 62){
Expand All @@ -104,7 +139,7 @@ class Integer
int64 self = unpack_int64(__self);
int64 mask = 1 << loc; $
return $ pack_bool(self & mask) $

set_bit(Integer loc)
$ int64 loc = unpack_int64(__loc);
if (loc < 1 or loc > 62){
Expand All @@ -114,7 +149,7 @@ class Integer
int64 self = unpack_int64(__self);
int64 mask = 1 << loc; $
return $ pack_int64(self | mask) $

remove_bit(Integer loc)
$ int64 loc = unpack_int64(__loc);
if (loc < 1 or loc > 62){
Expand All @@ -124,4 +159,3 @@ class Integer
uint64 self = (uint64) unpack_int64(__self);
int64 mask = 1 << loc; $
return $ pack_int64(self & (~mask)) $

3 changes: 3 additions & 0 deletions test/suite/stdlib.rip
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,9 @@ main()
Test.test("Integer.odd?", 8 .odd?(), false)
Test.test("Integer.even?", 7 .even?(), false)
Test.test("Integer.even?", 8 .even?(), true)
Test.test("Integer.to_string", 13.to_string(2, 0), "1101")
Test.test("Integer.to_string", 32.to_string(2, 0), "100000")
Test.test("Integer.to_string", 32.to_string(2, 8), "00100000")

# Tally results
arr = Test.get_results()
Expand Down

0 comments on commit 75c44db

Please sign in to comment.