开发者

Binary shift of int not possible

开发者 https://www.devze.com 2023-02-18 09:28 出处:网络
usigned int val = 1; val <<= 30; cout << intToBin(val) << endl; string intToBin(unsigned int val) {
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


Your while loop will not terminate if val is >= 2^31.

This is because k == 2^31 is still <= val but 2^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)

0

精彩评论

暂无评论...
验证码 换一张
取 消