Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix binary formatting for integers 2 and 3 #1123

Merged
merged 2 commits into from
Mar 26, 2024
Merged

Conversation

mierenhoop
Copy link
Contributor

Cosmopolitan's FormatBinary64 function gives incomplete representations of integers 2 and 3.
Shown in redbean's interpreter:

>: for i = 0, 8 do print(i, bin(i)) end
0       0
1       0b1
2       0b0
3       0b1
4       0b00000100
5       0b00000101
6       0b00000110
7       0b00000111
8       0b00001000

With the proposed patch, the ouput will look like this:

>: for i = 0, 8 do print(i, bin(i)) end
0       0
1       0b01
2       0b10
3       0b11
4       0b00000100
5       0b00000101
6       0b00000110
7       0b00000111
8       0b00001000

A different approach could be:

--- a/libc/fmt/formatbinary64.c
+++ b/libc/fmt/formatbinary64.c
@@ -21,7 +21,7 @@

 static inline int PickGoodWidth(unsigned x) {
   if (x < 16) {
-    if (x < 2) return 0;
+    if (x < 1) return 0;
     if (x < 8) return 7;
     return 15;
   } else {

Resulting:

0       0
1       0b1
2       0b00000010
3       0b00000011
4       0b00000100

Copy link
Owner

@jart jart left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. Thanks for sending this. Could you write the email mentioned in https://github.com/jart/cosmopolitan/blob/master/CONTRIBUTING.md Thank you!

Copy link
Owner

@jart jart left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please fix test/libc/fmt/formatbinary64_test.c too? Thanks!

@mierenhoop
Copy link
Contributor Author

Okay, now the tests are passing.

Copy link
Owner

@jart jart left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@jart jart merged commit 43885a7 into jart:master Mar 26, 2024
10 checks passed
@mierenhoop mierenhoop deleted the fix-bin-format branch March 29, 2024 16:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants