如何判断 32 位 int 是否适合 16 位 Short
仅使用:
! ~ & ^ | + << >>
我需要找出有符号的 32 位整数是否可以表示为 16 位二进制补码整数。
我的第一个想法是将 MSB 16 位和 LSB 16 位分开,然后使用掩码来处理最后 16 位,这样如果它不为零,则无法表示,然后使用该数字来检查 MSB 位。
我需要编写的函数示例是:fitsInShort(33000) = 0(无法表示)和fitsInShort(-32768) = 1(可以表示)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只是开玩笑:)这是真正的答案,假设 int 是 32 位,short 是 16 位,并且二进制补码表示:
编辑:请参阅最后的编辑以获得正确的答案!
没有 if 语句我相信应该做吧:
编辑:奥利是对的。我不知何故认为他们是被允许的。这是最后一次尝试,并附有解释:
我们需要
x
的 17 个最高有效位全为 1 或全为 0。因此,让我们从屏蔽其他位开始:或更简洁地说:
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
x
to be either all ones or all zeroes. So let's start by masking other bits out:Or more concisely:
如果 32 位数字在 [-32768,+32767] 范围内,则 17 个 msb 将全部相同。
这是一种仅使用您的操作来判断 3 位数字是全 1 还是全 0 的蹩脚方法(我假设您不允许使用条件控制结构,因为它们需要隐式逻辑操作):
我会离开你扩展/改进这个概念。
If a 32-bit number is in the range [-32768,+32767], then the 17 msbs will all be the same.
Here's a crappy way of telling if a 3-bit number is all ones or all zeros using only your operations (I'm assuming that you're not allowed conditional control structures, because they require implicit logical operations):
I'll leave you to extend/improve this concept.
这是一个没有强制转换、if 语句并且仅使用您要求的运算符的解决方案:
Here's a solution without casting, if-statements and using only the operators you asked for:
First
if
首先通过检查有符号位来检查 +ve 数字。如果 +ve ,则检查第 15 位到第 31 位是否为 0,如果为 0,则它不能适合short
,否则可以。如果位 15 至 31 全部设置(2 的补码方法表示),则负数在范围内。
因此,第二个
如果
它是一个-ve数,则位15到31被屏蔽,并且设置剩余的低位(0到14)。如果这是0xffffffff
,那么只有一个的补码将为0
,这表明位15到31都已设置,因此它可以适合(else部分),否则它不适合(if 条件)。First
if
Checks for +ve number first by checking the signed bit. If +ve , then it checks if the bit 15 to bit 31 are 0, if 0, then it cannot fit intoshort
, else it can.The negative number is withing range if bit 15 to 31 are all set (2's complement method representation).
Therefore The second
if
it is a -ve number, then the bit 15 to 31 are masked out and the remaining lower bits (0 to 14) are set. If this is0xffffffff
then only the one's complement will be0
, which indicates the bit 15 to 31 are all set, therefore it can fit (the else part), otherwise it cannot fit (the if condition).