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}
The simplest method is
Return (Val> 31) |-(-Val> 31 );