Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when I apply the unary "-" operator to an unsigned integer? [duplicate]

This should be a pretty simple question but I can't seem to find the answer in my textbook and can't find the right keywords to find it online.

What does it mean when you have a negative sign in front of an unsigned int?

Specifically, if x is an unsigned int equal to 1, what is the bit value of -x?

like image 689
user1888863 Avatar asked Apr 11 '16 06:04

user1888863


Video Answer


2 Answers

Per the C standard, arithmetic for unsigned integers is performed modulo 2bit width. So, for a 32-bit integer, the negation will be taken mod 232 = 4294967296.

For a 32-bit number, then, the value you'll get if you negate a number n is going to be 0-n = 4294967296-n. In your specific case, assuming unsigned int is 32 bits wide, you'd get 4294967296-1 = 4294967295 = 0xffffffff (the number with all bits set).


The relevant text in the C standard is in §6.2.5/9:

a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type

like image 105
nneonneo Avatar answered Sep 24 '22 21:09

nneonneo


It will overflow in the negative direction, i.e. if your int is 16 bits x will be 65535. The bit value will be 1111111111111111 (16 ones)

If int is 32 bits, x will be 4294967295

like image 38
Rishikesh Raje Avatar answered Sep 25 '22 21:09

Rishikesh Raje