# 问题:

Given any number, for example 345.678 and -345.678, what I want is to convert 345.678 to 1 and -345.678 to -1. Basically I want to convert any number to 1 or -1 with the sign kept via bit-wise operator.

Although I don't know why, I can convert any number into -1 like this:

``````345.678 | -1
``````

Any thoughts?

# 回答1:

You could take the idea of this question sign function in C using bit operators only

``````(x >> 31) & 1
``````

and adjust the result by taking bitwise OR instead of bitwise AND to get `1` instead of `0` and `-1` instead of `1`

``````const sign = x => (x >> 31) | 1;

console.log(sign(345.678));
console.log(sign(-345.678));``````

# 回答2:

For any integer number between -2147483648 and 2147483647, you can do:

``````(number >> -1) | 1
``````

It will return -1 if `number` is negative, and 1 if `number` is positive. For zero it will return 1.

It does not work with decimals in range `-1 < number < 0`! However it should work for other decimal numbers.

• 发表于 2019-07-04 18:32
• 阅读 ( 151 )
• 分类：sof

## 作家榜 »

1. 小编 文章