Thread: help

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    32

    help

    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?

  2. #2
    Registered User
    Join Date
    Jul 2005
    Posts
    21
    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.

  3. #3
    Registered User
    Join Date
    Mar 2009
    Posts
    31
    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.

  4. #4
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    The minimum signed value for a variable with 17 bits: -65 536

  5. #5
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by nonoob View Post
    The minimum signed value for a variable with 17 bits: -65 536
    it will depend on the negative value representation
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed