简体   繁体   English

在C中将整数转换为二进制字符串

[英]Converting an integer to binary strings in c

This is what I've tried, my logic is that my tmp shifting left 31 times will get compared to the user input integer I and a value of 1 or 0 will be inserted to index str[0] -> str[31] and the I null terminate str[32] with the \\0 . 这是我尝试过的,我的逻辑是将tmp向左移动31次将与用户输入的整数I进行比较,并将1或0的值插入到索引str[0] -> str[31] ,我用\\0终止str[32]

However, I'm getting a segmentation fault. 但是,我遇到了细分错误。

PS I'm not allowed to change the parameters of this function and my professor set the size of str to be 33 in the main, which, I'm not allow to change either. PS我不允许更改此函数的参数,我的教授在主体中将str的大小设置为33,这也不允许更改。

void int2bitstr(int I, char *str) {
        int tmp = 1 << 31;
        do{
                *str++ = !!(tmp & I) + '0';
        } while(tmp >>= 1);
        *str = '\0';
}

Try making tmp an unsigned int . 尝试将tmpunsigned int The behaviour of right-shifting a negative (signed) integer is implementation-defined, and in your case is likely shifting in 1s (the original MSB) thus causing the loop to exceed the length of str . 负数(有符号)整数右移的行为是由实现定义的,在您的情况下,很可能移位1s(原始MSB),从而导致循环超过str的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM