Evaluate the positive and negative integer features

Source: Internet
Author: User

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 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.