For a given 32-bit integer, write a function. If this number is positive, 1 is returned. If it is negative,-1 is returned, if it is set to zero, zero is returned, and no condition is required to judge the branch jump statement. Here, a slight extension is provided, indicating the corresponding unsigned 32-bit integer. The solution is to separate the signed bits and values. For a 32-bit integer, the signed bits are shifted to 31 To Get a. If it is not a negative number, a = 0x00000000; otherwise, a = 0 xFFFFFFFF; then, the values (0 or 1) are reduced and merged into one bit to get B. This is for the case of 0 and positive numbers, then, place a and B. The C ++ code is described as follows:
1 // If val is 0, 0 is returned. If val is negative,-1 is returned. If val is positive, 1 is returned.
2int32_t check32 (int32_t val)
3 {
4 int32_t a = val> 31;
5 int32_t B = (val & 0x0000FFFF) | (val> 16) & 0x0000FFFF );
6 B = (B & 0x000000FF) | (B> 8) & 0x000000FF );
7 B = (B & 0x0000000F) | (B> 4) & 0x0000000F );
8 B = (B & 0x00000003) | (B> 2) & 0x00000003 );
9 B = (B & 0x00000001) | (B> 1) & 0x00000001 );
10 return a | B;
11}
12
13 // If val is 0, 0 is returned; otherwise, 1 is returned.
14uint32_t check32 (uint32_t val)
15 {
16 uint32_t a = (val & 0x0000FFFF) | (val> 16) & 0x0000FFFF );
17 a = (a & 0x000000FF) | (a> 8) & 0x000000FF );
18 a = (a & 0x0000000F) | (a> 4) & 0x0000000F );
19 a = (a & 0x00000003) | (a> 2) & 0x00000003 );
20 a = (a & 0x00000001) | (a> 1) & 0x00000001 );
21 return;
22}
If anyone has a better solution, I 'd like to share more with you.