search
HomeBackend DevelopmentC#.Net TutorialDetailed explanation of decimal to binary, hexadecimal and octal conversion in C#

1. Convert decimal to binary

Continuously divide the decimal number by 2 and fill in all the remainders backwards to get the required binary data.

        public static string DecimalToBinary(int vDecimal)
        {/* 将十进制的数 vDecimal 不断地除 2,取余数
             * 然后将余数 倒序 填写             */List<int> vYuShu = new List<int>();  // 除 2 过程中产生的余数集int vTempValue= vDecimal;            // 除 2 过程中产生的商数for (; ; )
            {int tempYS = vTempValue % 2;
                vYuShu.Add(tempYS);  // 记住余数vTempValue = vTempValue / 2;if (vTempValue == 0)  // 商数等于0时,结束运算break;
            }// 倒序输出string strBinary = "";for (int i = vYuShu.Count - 1; i >= 0; i--)
            {
                strBinary += vYuShu[i];
            }

            Console.WriteLine("Input decimal value:{0}, output binary value:{1}.", vDecimal, strBinary);return strBinary;
        }</int></int>

##2. Convert binary to decimal

Multiply the value (0 or 1) in each binary digit by 2 raised to the (n-1) power, and convert each bit The results are added. Among them, n represents the number of digits from right to left in binary (counting from 1);

        public static int BinaryToDecimal(string vBinary)
        {// 首先判断是否满足输入要求int[] vInput = new int[vBinary.Length];for (int i = 0; i <div class="cnblogs_code"></div><p><strong> <span style="font-size: 14pt"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/001/053e340232d19ddde4b2cb7c71ab5415-1.png?x-oss-process=image/resize,p_40" class="lazy" alt=""></span></strong></p> <p></p><p><strong>3. Built-in conversion method<span   style="max-width:90%"></span></strong></p> C#.Net’s built-in base conversion method:<p></p><pre class="brush:php;toolbar:false">            int vDecimal = 99;// 【10】 → 【2】string vBinary = Convert.ToString(vDecimal, 2);
            Console.WriteLine("十进制数:{0},转换成二进制:{1}", vDecimal, vBinary);// 【2】 → 【10】int tempDecimal = Convert.ToInt32(vBinary, 2);
            Console.WriteLine("二进制数:{0},转换成十进制:{1}", vBinary, tempDecimal);

#4. Decimal Hexadecimal

            int vDecimal = 127;// 【10】 → 【16】string vStrHex = "0x" + Convert.ToString(vDecimal, 16);
            Console.WriteLine("十进制数:{0},转换成十六进制:{1}", vDecimal, vStrHex);// 【16】 → 【10】int tempDecimal = Convert.ToInt32(vStrHex, 16);
            Console.WriteLine("十六进制数:{0},转换成十进制:{1}", vStrHex, tempDecimal);

## Or you can:

##5. Decimal Octal

##6. Other conversions

7. Signed number binary conversion

For data with positive and negative signs, the conversion is slightly different from the appeal.

1 byte (8 bits) can only represent 256 numbers anyway. Because it is signed, we express it as a range: -128 → 127.

Use the highest bit to represent the sign bit, 0 represents a positive number, and 1 represents a negative number.

10000000 represents the smallest negative integer in the computer. From 10000001 to 11111111, it means -127 to -1.

Negative integers are stored in two's complement form in computers.

        public static int BinaryToDecimalWithSign(string vBinary)
        {// 首先判断是否满足输入要求int[] vInput = new int[vBinary.Length];for (int i = 0; i <em></em>

[]

The above is the detailed content of Detailed explanation of decimal to binary, hexadecimal and octal conversion in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.