C# program to calculate total number of digits in a number

王林
Release: 2023-09-12 15:25:02
forward
1150 people have browsed it

C# 程序计算数字中的总位数

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;
Copy after login

12 is −

1100
Copy after login

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;
Copy after login

Example

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);
   }
}
Copy after login

Output

Total bits: 4
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template