Check if an integer is a power of 2

Started by TomToad, October 31, 2018, 19:33:51

Previous topic - Next topic

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++
// 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;
}


BlitzMax
SuperStrict
For Local i:Int = 0 To 65536
If (i And Not (i&(i-1))) Then Print i
Next
------------------------------------------------
8 rabbits equals 1 rabbyte.