2013-05-14 31 views
1

这段代码是一个函数的一部分,它将十进制数字转换为二进制数据,并将其置于char instBin [33]的特定索引中由调用函数创建并通过引用传递。它传递十进制数字,你想要的二进制数字的数量(将额外的0附加到给定的二进制数字的前面)。我一直在摆弄这一段时间,我无法将0和1放入阵列。我已经完成了一步到实现instBin [i] ='1';根本不工作 - 当我打印instBin时,什么也没有发生。我已经看过其他的例子做这种类型的事情,但似乎给一个字符数组选择索引时应该工作...任何想法,为什么我的不是?C - 使用循环和索引填充字符* NOT WORKING

int printBin(int num, int numBits, int startIndex, char * instBin){ 
    int r, i; /* r for remainder, i for index */ 
const int FAIL = 0; 
i = startIndex + numBits; /* start indexing at end of current segment */ 
while (num > 0) 
{ 
    /* as long as i >= startIndex, we can still add to array */ 
    if (i >= startIndex){ 
     r = num % 2; /* find the remainder */ 
     if (r == 1) 
      instBin[i] = '1'; 
     else /* r == 0 */ 
      instBin[i] = '0'; 
     num /= 2; /* then actually divide the number */ 
     i--; 
    } 
    else /* num is too big to fit in given number of bits */ 
    return FAIL; 
} 
/* return the 1 for success*/ 
return 1; 
} 
+0

欢迎堆栈溢出。请尽快阅读[常见问题]。请显示函数定义行(带有返回类型,函数名称和参数声明的行)!有FAIL定义是很好的;为什么不定义PASS或SUCCESS或其他呢?在Unix上,系统函数通常会返回0以取得成功 - 这与您使用的约定相反。 – 2013-05-14 02:57:42

+0

提示:你可以简单写'instBin [i] ='0'+ num%2;'。像'/ *发现剩余* /'这样的注释不会将任何信息添加到您的代码中。 – Elazar 2013-05-14 03:05:21

+0

好的建议,谢谢!哦,对于Sergi0,instBin被定义为:char instBin [33]; //一个空字节点 – 2013-05-14 03:09:14

回答

0

有两个主要问题。第一个是fencepost错误。假设你的意图是最重要的位将被放入缓冲区startIndex,你需要从i = startIndex + numBits - 1开始。如果您需要说服这一点,请考虑使用numBits = 1

第二个问题是,当数量足够小以至于需要前导零时,循环不提供它们。它一次提供一位数字,直到数字达到0,然后停止。在主循环之后需要第二个循环来添加零。如果你看看i主循环后的值,它会告诉你在哪里主循环停止,这样你就可以完成这项工作是这样的:

while(i >= startIndex) 
    instBin[i--] = '0';