设置整个字节如果第一个位是1
我正在尝试制作程序,例如273(000100010001B)
制作4095(111111111111b)
。
有趣的部分是我的程序适用于第一个迭代,例如17(00010001b)
正确返回255(11111111b)
,但之后的每个字节都不起作用。例如,273(000100010001b)
返回61951(1111000111111111b)
,我无法弄清楚为什么是这样。
这是我的代码
int x,temp, i;
int mask = 15;
scanf_s("%d", &x);
temp = x;
for(i=0;i<4;i++){
mask<<=i*4;
if((temp&1)==1){
x|=mask;
} else{
}
temp>>=4;
}
printf("%d", x);
I'm trying to make program that will for for example 273(000100010001b)
make to 4095(111111111111b)
.
Funny part is that my program works for first 2 iterations, for example 17(00010001b)
correctly returns 255(11111111b)
but every byte after that doesn't work. For instance 273(000100010001b)
returns 61951(1111000111111111b)
and I cant figure out why is that.
Here is my code
int x,temp, i;
int mask = 15;
scanf_s("%d", &x);
temp = x;
for(i=0;i<4;i++){
mask<<=i*4;
if((temp&1)==1){
x|=mask;
} else{
}
temp>>=4;
}
printf("%d", x);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您在
Mask
上执行的偏移。您在第1次迭代中将其移至0,在第二个迭代中将其移动4,第三次迭代中的12(4 + 8)等等。另外,您不会在
temp
的所有位上应用蒙版。我无法确定您是否故意这样做。在这里,您是一个固定版本:
我的结果是:
The issue is the shift you perform on
mask
. You shift it by 0 on the 1st iteration, 4 on the 2nd, 12 (4 + 8) on the 3rd and so on.Also, you don't apply the mask over all the bits of
temp
. I can't tell if you do this on purpose.Here you are a fixed version:
My results are: