Assuming a 17-bit integer, does the following statement result in overflow? Explain your answer.
int x = 50210;
how would i solve this or find an answer to this?
Assuming a 17-bit integer, does the following statement result in overflow? Explain your answer.
int x = 50210;
how would i solve this or find an answer to this?
While x is greater than 0, you'd divide x by 2 (assigning the result back to x), the number of times it does this division is equal to the number of bits required to represent the number.
Of course you'd need to be aware that diving an odd number by 2 would result in a rational number (floating point), but with integer division being the case it will be rounded down anyway.
When counting in binary there are simple ways to check if the storage-variable could hold the value you would like to assign it.
First of all you should read-up with the binary numeral system, when done with that you should understand how everything works - but read ahead if you not fully understand.
The maximum value a unsigned variabel with n bytes can hold is "(2^n)-1".
if you decrement this value by 1 and then divide it by 2 you will get the +/- max/min of the same variable, but signed. This is called "two complement"
The maximum unsigned value for a variable with 17 bits is: (2^17)-1 = 131 071
The minimum signed value for a variable with 17 bits: 0.5 * ((2^17)-1-1) * -1 = -65 535
The maximum signed value for a variable with 17 bits is: 0.5 * ((2^17)-1-1) = 65 535
Answer: assigning 50 210 to a (signed) integer would not result in an overrun/overflow.
The minimum signed value for a variable with 17 bits: -65 536