确定32位int的符号 [英] Determine the sign of a 32 bit int
本文介绍了确定32位int的符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
仅使用:
! 〜& ^ | +<< >>
! ~ & ^ | + << >>
没有麻烦
我需要确定32位整数的正负号,如果为正,则需要返回1,如果为0,则需要返回0,如果为负,则需要返回-1.
I need to determine the sign of a 32 bit integer and I need to return 1 if positive, 0 if 0 and -1 if negative.
有什么想法吗?我首先考虑过移31位,然后看那个符号,但是那显然不起作用,现在我有点卡住了.
Any ideas? I first thought about shifting over 31 bits and then looking at that sign but that obviously wont work and now I am kind of stuck.
推荐答案
尝试一下:
(x >> 31) | (((0 - x) >> 31) & 1)
如何?
(x >> 31) | (((~x + 1) >> 31) & 1)
针对评论中提出的问题(或更确切地说是挑剔的问题)...
In response to issues (or rather nit-picking) raised in the comments...
这些解决方案有效的假设:
Assumptions for these solutions to be valid:
- x是32位有符号整数类型.
- 在此系统上,带符号的32位整数是二进制补码. (右移是算术运算)
- 算术溢出的环绕式.
- 对于第一个解决方案,文字
0
与x的类型相同.
- x is of type 32-bit signed integer.
- On this system, signed 32-bit integers are two's complement. (right-shift is arithmetic)
- Wrap-around on arithmetic overflow.
- For the first solution, the literal
0
is the same type as x.
这篇关于确定32位int的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文