Let us assume that the number we have is 12. We declared and initialized a uint variable by assigning a decimal literal. The binary representation of
uint val = 12;
12 is −
1100
The number of digits above is 4, so to find the total number of digits, use the Math.log() method−
uint res = (uint)Math.Log(val , 2.0) + 1;
You can try running the following code to calculate the total number of digits in a number.
Live Demo
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); } }
Total bits: 4
The above is the detailed content of C# program to calculate total number of digits in a number. For more information, please follow other related articles on the PHP Chinese website!