那么...您是否检查了代码的输出以了解它为什么不起作用?
So iteration 1 of your loop:
value = 192
i = 4
output[i] = (11000000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 2 of your loop:
value = 96
i = 3
output[i] = (1100000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 3 of your loop:
value = 48
i = 2
output[i] = (110000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 4 of your loop:
value = 24
i = 1
output[i] = (11000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 5 of your loop:
value = 12
i = 0
output[i] = (1100 & 1) + '0' = 0 + 48 = 48 (char `0`)
Final string: "00000" and you wanted: "11000000"
看到你的代码有什么问题吗?没有。我也没有,你只是还不够远。将您的输出/循环更改为:
output[8] = '\0';
for (i = 7; i >= 0; --i, value >>= 1)
然后您将返回正确的结果。
我会推荐一种更通用的方法,您使用的是固定长度的字符串,这将您限制为一定长度的二进制数。您可能想要执行以下操作:
loop while number dividing down is > 0
count number of times we loop
malloc an array the correct length and be returned