Skip to content

Commit

Permalink
[translation] Implement hex and octal conversion functions.
Browse files Browse the repository at this point in the history
They're similar to str(), except base 8 and 16.

Crestwave's brainfuck runs on Hello World!
  • Loading branch information
Andy Chu committed Jul 14, 2020
1 parent a2b717f commit 35066bf
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
12 changes: 9 additions & 3 deletions mycpp/mylib.h
Original file line number Diff line number Diff line change
Expand Up @@ -1248,15 +1248,21 @@ inline Writer* Stderr() {
}

inline Str* hex_lower(int i) {
assert(0);
char* buf = static_cast<char*>(malloc(kIntBufSize));
int len = snprintf(buf, kIntBufSize, "%x", i);
return new Str(buf, len);
}

inline Str* hex_upper(int i) {
assert(0);
char* buf = static_cast<char*>(malloc(kIntBufSize));
int len = snprintf(buf, kIntBufSize, "%X", i);
return new Str(buf, len);
}

inline Str* octal(int i) {
assert(0);
char* buf = static_cast<char*>(malloc(kIntBufSize));
int len = snprintf(buf, kIntBufSize, "%o", i);
return new Str(buf, len);
}

} // namespace mylib
Expand Down
9 changes: 9 additions & 0 deletions mycpp/mylib_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,15 @@ TEST test_str_funcs() {
int_str = str(-(1 << 31));
log("i = %s", int_str->data_);

int_str = mylib::hex_lower(15);
ASSERT(str_equals0("f", int_str));

int_str = mylib::hex_upper(15);
ASSERT(str_equals0("F", int_str));

int_str = mylib::octal(15);
ASSERT(str_equals0("17", int_str));

Str* s1 = new Str("abc\0bcd", 7);
ASSERT_EQ(7, len(s1));

Expand Down

0 comments on commit 35066bf

Please sign in to comment.