General Category > General Game and Application Development

Check if an integer is a power of 2

(1/1)

TomToad:
Had the need to see if an integer is a power of 2 or not.  Came across this formula
(x && (!(x&(x-1))))
C/C++

--- Code: ---// ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>


int main()
{
for (int i = 0; i <= 65536; i++)
if (i && (!(i&(i - 1))))
std::cout << i << std::endl;
    return 0;
}

--- End code ---

BlitzMax

--- Code: ---SuperStrict
For Local i:Int = 0 To 65536
If (i And Not (i&(i-1))) Then Print i
Next

--- End code ---

Navigation

[0] Message Index

Go to full version