Obtain the signed digits of integers and floating-point numbers in C.
1. Why do I need to get the symbol bit?
In many cases, we need to determine the positive and negative values for corresponding logic processing. The condition judgment statement can well meet this requirement. Sometimes there are the following situations,
if (x > 0) { x = x - 1;} else { x = 1 - x;}if (x < 0) { x = -x;}
Positive and negative are only changes in the symbol bit of the value, or the symbol bit of the calculation result. However, we need to use a judgment. First, the condition judgment will affect the efficiency. Second, the format is not concise and beautiful. Therefore, you may want to solve the problem without conditional judgment. The symbol bit of the value has been stored in the highest bit of the value, which can be used to avoid conditional judgment.
2. How to obtain the symbol bit
There may be many methods. However, it is most directly thought of to get the symbol bit through shift. Shift has shifted left to right because of the symbol bit. Therefore, there are two cases where there are shifts to the right of the symbol and shifts to the right without the symbol. The signed right-shift vacancy sign-in and the unsigned right-shift vacancy sign-In are 0. When a signed number and a signed bit are moved to the first place on the right,-1 indicates a negative number and 0 indicates a positive number. When you move the unsigned number and the signed bit to the first place on the right, result 1 is a negative number with a positive value of 0.
3. An Implementation Method
Because floating point numbers cannot be displaced, either convert them into integers or split them into arrays. Here we use it as an array.
First, we treat the numeric value as a char [] array regardless of its type,
(signed char*) &x
In this way, the values are split into multiple char-type spaces, and the symbol bit is stored in the char space with the highest bit.
((signed char*) &x)[sizeof(x) - 1]
Assume that the small-end storage mode is used, and the symbol bit is in the last space of the char array. We get the char data with a signed bit and process it as a signed number.
((signed char*) &x)[sizeof(x) - 1] >> 7
7-bit shift to the right indicates that the symbol is moved to the first place on the right. Then, the positive number is 0, and the negative number is-1.
Finally, complete macro definition
/** * Get x sign bit only for little-endian * if x >= 0 then 1 * if x < 0 then -1 */#define MathUtils_SignBit(x) \(((signed char*) &x)[sizeof(x) - 1] >> 7 | 1)
The result is mapped to 1 or [0,-1] to [1,-1], so that we can write the initial example as follows:
x = (x - 1) * MathUtils_SignBit(x)x *= MathUtils_SignBit(x)