int 不可能进行二进制移位
usigned int val = 1;
val <<= 30;
cout << intToBin(val) << endl;
string intToBin(unsigned int val) {
unsigned int k=1;
string ret;
while (k <= val) {
if (k & val) {
ret.insert(0,"1");
} else {
ret.insert(0,"0");
}
k <<= 1;
}
return ret;
}
这将写入 1 和 30x 0,这是可以的。但我需要的是在最高位上有 1,这意味着在第一个位置 - 后面跟着 31 个零。但是当我尝试 val <<= 31;什么也没写,我看不懂。您能为我澄清一下吗?
谢谢
usigned int val = 1;
val <<= 30;
cout << intToBin(val) << endl;
string intToBin(unsigned int val) {
unsigned int k=1;
string ret;
while (k <= val) {
if (k & val) {
ret.insert(0,"1");
} else {
ret.insert(0,"0");
}
k <<= 1;
}
return ret;
}
This will write 1 and 30x 0 which is alright. But what I need is to have the 1 on the highest bit, meaning on the first position - followed by 31x zeros. But when I try to val <<= 31; nothing is written, which I don't understand. Could you clarify that for me please?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
val
为>= 2^31
,您的 while 循环将不会终止。这是因为
k == 2^31
仍然是<=
val
但2^31 << 1 == 2^32
溢出并变为 0。这仍然小于限制。您也可以扩展您的条件以中断 if
k == 0
,那么问题应该消失。(本文中
^
表示求幂而不是异或)Your while loop will not terminate if
val
is>= 2^31
.This is because
k == 2^31
is still<=
val
but2^31 << 1 == 2^32
overflows and becomes 0. Which is still smaller than the limit.You could extend your condition to break if
k == 0
too, then the problem should disappear.(
^
means exponentiation not xor in this post)