Let us say the number we have is 12. We have declared and initialized a uint variable by assigning a decimal literal,
uint val = 12;
The binary representation of 12 is −
1100
The bits above is 4, therefore to find the total bits, use the Math.log() method −
uint res = (uint)Math.Log(val , 2.0) + 1;
Example
You can try to run the following code to count total bits in a number.
using System;
public class Demo {
public static void Main() {
uint val = 12; // 1100 in binary
uint res = (uint) Math.Log(val, 2.0) + 1;
// 1100 has 4 bits
Console.WriteLine("Total bits: " + res);
}
}Output
Total bits: 4