Using only:
! ~ & ^ | + << >>
I need to find out if a signed 32 bit integer can be represented as a 16 bit, two’s complement integer.
My first thoughts were to separate the MSB 16 bits and the LSB 16 bits and then use a mask to and the last 16 bits so if its not zero, it wont be able to be represented and then use that number to check the MSB bits.
An example of the function I need to write is: fitsInShort(33000) = 0 (cant be represented) and fitsInShort(-32768) = 1 (can be represented)
Just kidding 🙂 Here’s the real answer, assuming int is 32 bits and short is 16 bits and two’s complement represantation:
Edit: Please see the last edit for the correct answer!
Without if statements i beleive that should do it:
Edit: Oli’s right. I somehow thought that they were allowed. Here’s the last attempt, with explanation:
We need the 17 most significant bits of
xto be either all ones or all zeroes. So let’s start by masking other bits out:Or more concisely: