# Include <iostream> using namespace STD; int numonesinbinary (INT num) // counts the representation of a number in the memory. There are several 1 {int numones = 0; while (num! = 0) {num = num & num-1; numones ++;} return numones;} void main () {int A =-1; unsigned int B = 2; cout <(unsigned INT) A <Endl; cout <a + B <Endl; A =-3; // [if you have any questions,] cout <a + B <Endl; // The result is unsigned int} {short a =-1; unsigned short B = 2; cout <(unsigned short) A <Endl; cout <a + B <Endl; A =-3; // [Have questions here] // enter the question and above Code Is the output inconsistent when it is int? Cout <a + B <Endl; // Why not 65535? Isn't the result after a + B an unsigned number? } Int a1 =-1; int a2 = 88; cout <(A1 & A2) <Endl; // bitwise AND, -1 memory is represented as 32 1 int ival =-1; cout <"The num of 1 in momory is:" <numonesinbinary (ival) <Endl; {// The unsigned number arithmetic operation does not overflow: Unsigned short b1 = 65530; unsigned short b2 = 5000; cout <"B1 + b2 =" <B1 + b2 <Endl ;}{// when calculating addition, the signed short is promoted to unsigned short first, so there is no overflow saying that unsigned short b1 = 65530; short b2 = 5000; cout <"B1 + b2 =" <B1 + b2 <Endl ;} {// overflow short b1 = 65530; short b2 = 5000; cout <"B1 + b2 =" <B1 + b2 <Endl ;}getchar ();}
Note:
1) The numonesinbinary function is applicable to positive and negative numbers.
2) [if you have any questions here] I don't understand. The result of the unsigned number and the signed number arithmetic operation should be the unsigned number. Why is there an output-1? If you happen to see this article, please kindly advise.
3) & bitwise AND, that is, bitwise and in the memory representation. Any number and-1 are bitwise AND, and the result is itself.
Overflow of arithmetic operations:
There are two types of integer arithmetic operations in C language: signed and unsigned.
In unsigned arithmetic operations, there is no such thing as "overflow ".: All unsigned operations are modeled on the N power of 2, where N is the number of digits in the result.
If one operand of an arithmetic operation is a signed integer and the other is an unsigned integer, the signed integer is converted to an unsigned integer before the operation, and "overflow" is impossible.
When both operands are signed integers, "overflow" may occur.
Example
Assuming that A and B are two non-negative integer variables, how can we check whether a + B overflows?
If(A+B<0)// ErrorComplain();If((Unsigned)A+ (Unsigned)B>Int_max)// OK, where is int_max? <Limits. h>Complain();If(A>Int_max-B)// OKComplain();