Skip to content

Commit a5e901b

Browse files
committed
Fix the conversion process from an integer to an octal string
The implementation of __str_base8() produces incorrect conversions when handling negative integers. For example, a 32-bit negative integer '0xfffff204', it will produce '7' at the most significant digit due to sign extension. However, it should produce '3' by using the leftmost 2 bits only. Therefore, this commit modifies the conversion process to fix the mentioned problem.
1 parent c2e0383 commit a5e901b

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

lib/c.c

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,13 +166,24 @@ void __str_base10(char *pb, int val)
166166

167167
void __str_base8(char *pb, int val)
168168
{
169-
int c = INT_BUF_LEN - 1;
170-
while (c > 0) {
171-
int v = val & 0x7;
169+
int c = INT_BUF_LEN - 1, v;
170+
/*
171+
* Because every 3 binary digits can be converted
172+
* to 1 octal digit, here performs the conversion
173+
* 10 times, derived from 32 divided by 3.
174+
*
175+
* Finally, the remaining 2 bits are processed after
176+
* the loop.
177+
* */
178+
int times = (sizeof(int) << 3) / 3;
179+
for (int i = 0; i < times; i++) {
180+
v = val & 0x7;
172181
pb[c] = '0' + v;
173182
val = val >> 3;
174183
c--;
175184
}
185+
v = val & 0x3;
186+
pb[c] = '0' + v;
176187
}
177188

178189
void __str_base16(char *pb, int val)

0 commit comments

Comments
 (0)