c - 我的二进制到十进制方法的无限循环错误?

标签 c while-loop binary bit

我的方法出现无限循环,我不确定为什么。我正在研究一种将十进制位转换为二进制形式的方法。我看不到发生了什么,因为运行此方法时出现无限循环。我希望我能得到一些帮助,为什么。

这是我的代码:

int binToDec(char* bin)
{       
        int i = 0;

        int result = 0; // (1) start the decimal result at 0.   
        while(bin != "\n");// (2) remove the most significant binary digit(leftmost) and add it to the result.
        {

        if(bin[i] == '1')
        {       
                result = result * 2 + 1;
        }
        else if(bin[i] == '0')
        {       
                result *= 2;
        } 
        printf("%d\n", result);
        i++;    
        }       // (3) If all binary digits have been removed, you're done. Stop.
                // (4) Otherwise, multiply the result by 2 and go back to step 2.
        return result;
}
/**
 * Create two functions that do binary to decimal conversion and back. Their signatures (aka prototypes)
 * should look like:
 * int binToDec(char* bin);
 * char* decToBin(int dec);
 *
 * For both functions, remember that your string will not hold 0s and 1s, but the characters ‘0’ and ‘1’. 
 * Use the offset to determine the binary value.      
 */
    char* decToBin(int dec)
{

        int i;
        double z;
        for(i = 0; i < dec; i++)
        {
                 z = pow(2, i);
                printf("The bit is %d \n", z);
        }
        char *c = (char*) malloc(dec * sizeof(z));

        while(dec % 2 != 0) //As long as the quotient is not 0, continue to divide the newest quotient by 2.
        {
                c[i] +=  dec % 2 + '0';
                dec = dec / 2; //Divide the value by 2 and record the remainder.        
        i++;
        }
        return c;
}
int main()
{
        int num;
        char *ptr;
        ptr = (char*) malloc(num * sizeof(decToBin(11001)));

        printf("Call to binToDec given 1001 result in: %d\n", binToDec("11001"));
        printf("Call to decToBin given 9 results in : %s\n", decToBin(11001));
        free(ptr);
        return 0;
}

让我知道。无限循环发生在第一种方法中。

最佳答案

看这一行:

while(bin != "\n");

即使 ; 不存在,条件也永远不会成立,因为您无法像这样比较字符串。一定是

while( strcmp(bin, "\n") != 0 )

但是看看显然应该是循环体的内容,您不会增加指针bin,而是增加整数i。所以最后,你的条件应该是

while( strcmp(bin+i, "\n") != 0)

或者简单地

while( bin[i] != '\n' )

...并且没有“;”当然

正如 @barmar 正确提到的,如果您使用根本不包含换行符的字符串调用 binToDec() ,您仍然会陷入无限循环。因此,因为 bin 应仅由 '0''1' 组成,我建议:

  while( bin[i] == '0' || bin[i] == '1' ) 

或者,如果您想支持“格式化”二进制字符串(例如,每 8 位数字后有一个空格)

  while( bin[i] != '\0' && bin[i] != '\n' ) 

你的循环体已经很好了,因为如果 bin[i] 既不是 '0' 也不是 '1',你什么也不做

关于c - 我的二进制到十进制方法的无限循环错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58380754/

相关文章:

python - 读取一位操作python 2.6

c++ - Arduino - 为什么串行数据以错误的顺序写入?

c - 停留在 while 循环中

java - (reader.ready()) 和使用 for 循环读取文件有什么区别?

binary - 十进制 float 与二进制的相互转换

php - 将二进制转换为字符串然后再转换回二进制

c - 从 C 语言的输入文件中读取 CJK 字符

c - 在c中打印链表值时出现奇怪的值

java - 在 JNA 中创建全局引用

python - 计算限制内的数据点,并对孤立点应用缓冲区[数据分析]