简体   繁体   中英

negative value stored in unsigned int

we know if we want to store num=-1 in 32 bit signed int its bits representation will look like 1000 0000 0000 0000 0000 0000 0000 0001

but if I do like this num=-1 unsigned int num1 = num then num1 bit representation will look like 1111 1111 1111 1111 1111 1111 1111 1111 .

we also know that in unsigned int msb does not represent sign,it contributes to magnitude,I want to know why there are all ones in num1 representation how can I predict the value for -2 in unsigned int

Note I was trying all the operation in cpp language

#include<bits/stdc++.h>
using namespace std;
int main(){
    unsigned int num = -1;
    ///i want to know what will be the bit representation of num=-2
    while(num){
        cout<<(num&1);
        num>>=1;
    }

}

As you said, the MSB of unsigned ints contributes to magnitude, as do all the other bits. You can see since unsigned int num1 = -1 gives 1111 1111 1111 1111 1111 1111 1111 1111 which is the greatest possible unsigned value (2^32). -2 is literally num1 - 1 . Therefore you can just subtract 1 and get 1111 1111 1111 1111 1111 1111 1111 1110 (2^32 - 1).

https://www.tutorialspoint.com/two-s-complement

When you assigned a negative number to unsigned int the negative number as you said the first bit is sign bit and the other is binary of the number for example binary representation -2 is 1000 0000 0000 0000 0000 0000 0000 0010 unsigned int get two's complete of this number.If you want to convert the signed binary to two's complete from first 1 from right every bit get not except for signed bit so two's complete of -2 should be 1111 1111 1111 1111 1111 1111 1111 1110.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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