我写了这个程序,用按位操作练习自己。在以下代码行中,我尝试逐位将值分配给三个short
。然后我通过bit_print()
函数打印它们。
#include <stdio.h>
#include <limits.h>
void bit_print(short a)
{
int i;
int n = sizeof(short) * CHAR_BIT; /* in limits.h */
short mask = 1 << (n - 1); /* mask = 100...0 */
for (i = 1; i <= n; ++i) {
putchar(((a & mask) == 0) ? '0' : '1');
a <<= 1;
if (i % CHAR_BIT == 0 && i < n)
putchar(' ');
}
}
int main(void){
short alice = 0, betty = 0, carol = 0;
int x;
char c;
printf("Put 16 bits for Alice: ");
for (x = 15; x >= 0; --x){
if ((c = getchar()) == '1')
alice |= 1 << x;
else
alice |= 0 << x;
}
putchar('\n');
printf("Put 16 bits for Betty: ");
for (x = 15; x >= 0; --x){
if ((c = getchar()) == '1')
betty |= 1 << x;
else
betty |= 0 << x;
}
putchar('\n');
printf("Put 16 bits for Carol: ");
for (x = 15; x >= 0; --x){
if ((c = getchar()) == '1')
carol |= 1 << x;
else
carol |= 0 << x;
}
putchar('\n');
bit_print(alice);
putchar('\n');
bit_print(betty);
putchar('\n');
bit_print(carol);
putchar('\n');
return 0;
}
出于某种原因,如果我输入1111111111111111三次,执行程序我得到以下输出:
Put 16 bits for Alice: 1111111111111111
Put 16 bits for Betty: 1111111111111111
Put 16 bits for Carol: 1111111111111111
11111111 11111111
01111111 11111111
10111111 11111111
正如你所看到的,最后两个变量中最重要的部分,betty和carol,在不应该的地方有零。 为什么呢?
答案 0 :(得分:1)
使用getchar()
时,您输入结束输入结尾的换行符会被拾取,但您没有考虑它。
您需要在每个循环结束时阅读并放弃换行符以解释此问题:
#include <stdio.h>
#include <limits.h>
void bit_print(short a)
{
int i;
int n = sizeof(short) * CHAR_BIT; /* in limits.h */
short mask = 1 << (n - 1); /* mask = 100...0 */
for (i = 1; i <= n; ++i) {
putchar(((a & mask) == 0) ? '0' : '1');
a <<= 1;
if (i % CHAR_BIT == 0 && i < n)
putchar(' ');
}
}
int main(void){
short alice = 0, betty = 0, carol = 0;
int x;
char c;
printf("Put 16 bits for Alice: ");
for (x = 15; x >= 0; --x){
if ((c = getchar()) == '1')
alice |= 1 << x;
else
alice |= 0 << x;
}
putchar('\n');
getchar();
printf("Put 16 bits for Betty: ");
for (x = 15; x >= 0; --x){
if ((c = getchar()) == '1')
betty |= 1 << x;
else
betty |= 0 << x;
}
putchar('\n');
getchar();
printf("Put 16 bits for Carol: ");
for (x = 15; x >= 0; --x){
if ((c = getchar()) == '1')
carol |= 1 << x;
else
carol |= 0 << x;
}
putchar('\n');
getchar();
bit_print(alice);
putchar('\n');
bit_print(betty);
putchar('\n');
bit_print(carol);
putchar('\n');
return 0;
}