Round up the provided value to the nearest power of 2 by bit operation. - CSharp System

CSharp examples for System:Bit

Description

Round up the provided value to the nearest power of 2 by bit operation.

Demo Code

// This library is free software; you can redistribute it and/or
using System.Text;
using System.Collections.Generic;
using System.Collections;
using System;/*  w w w.j ava  2s  .com*/

public class Main{
        /// <summary>
        /// Round up the provided value to the nearest power of 2.
        /// Taken from  Sean Anderson's 
        /// <a href="http://www-graphics.stanford.edu/~seander/bithacks.html">
        /// BitWiddling Hacks</a>.
        /// </summary>
        public static uint RoundUpToPowerOf2(uint v)
        {
            // compute the next highest power of 2 of 32-bit v
            if (v == 0) { return 1; }   // otherwise 0 => 0
            v--;    // 0 - 1 => 2^32
            v |= v >> 1;
            v |= v >> 2;
            v |= v >> 4;
            v |= v >> 8;
            v |= v >> 16;
            return v + 1;
        }
}

Related Tutorials