Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-6228

"std::has_single_bit" should be used to test if an integer is a power of two

    XMLWordPrintable

    Details

    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Targeted languages:
      C++
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      2min
    • Analysis Level:
      Syntactic Analysis
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      Since integers are usually represented in binary form in computers, is it efficient to check if a given number is a power of two, by checking if its unsigned representation has a single bit set.

      In C++ such check could be expressed as x & (x-1) == 0. However, the intent of this expression is unclear. Furthermore, it requires to take special care for the value 0, which would pass the above check, while not having any bit set and not being a power of two.

      This check can be expressed more clearly with the std::has_single_bit function template, introduced in C++20.

      This rule reports computations that could be replaced with std::has_single_bit .

      Noncompliant Code Example

      void f(unsigned x) {
        if ((x > 0) && !(x & (x-1))) { // Noncompliant
          // Special algorithm for powers of 2
        }
        // Normal algorithm   
      }
      

      Compliant Solution

      void f(unsigned x) {
        if (std::has_single_bit(x)) {
          // Special algorithm for powers of 2
        }
        // Normal algorithm   
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              tomasz.kaminski Tomasz KamiƄski
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: