/* Converts the unsigned integer k to binary character form with a blank
after every fourth digit. Result is in string s of length 39. Caution:
If you want to save the string, you must move it. This is intended for
use with printf, and you can have only one reference to this in each
printf statement. */
char * binary(unsigned k) {
int i, j;
static char s[40] = "0000 0000 0000 0000 0000 0000 0000 0000";
j = 38;
for (i = 31; i >= 0; i--) {
if (k & 1) s[j] = '1';
else s[j] = '0';
j = j - 1;
k = k >> 1;
if ((i & 3) == 0) j = j - 1;
}
return s;
}
我用c++测试过
#include <iostream>
using namespace std;
char *binary(unsigned k){
int i, j;
static char s[40]="0000 0000 0000 0000 0000 0000 0000 0000";
j=38;
for (i=31;i>=0;i--){
if (k & 1) s[j]='1';
else s[j]='0';
j=j-1;
k=k>>1;
if ((i & 3)==0) j=j-1;
}
return s;
}
int main(){
unsigned k;
cin>>k;
*binary(k);
return 0;
}
但是 k 有什么值(value)呢?例如我输入了 127 但它返回 0 为什么?
最佳答案
您正在丢弃函数 binary
的返回值:
*binary(k);
binary
返回一个 char *
,它(如文档所述)“旨在与 printf 一起使用”,但您没有对该字符串执行任何操作。您的程序“返回”0,因为这是您在最后一行代码中明确返回的内容!
尝试改变
*binary(k);
到
cout << binary(k);
你至少应该看到一些输出。
关于c++ - 黑客喜欢的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3253349/