21/04/2016

[C# .NET] Convert Between Hexadecimal, Decimal, Octal, Binary With C#


Để chuyển đổi qua lại giữa các hệ cơ số trong lập trình C# bạn có thể tham khảo các phương thức sau đây.

Bài liên quan
Hexadecimal, Decimal, Octal, Binary


1. Hex

a.) Decimal

//Hex to Dec
var hex = "7E0";
var dec = Convert.ToInt32(hex, 16); //2016
//Dec to Hex
var hex2 = dec.ToString("X"); //7E0

b.) Octal

//Hex to Octal
var hex = "7E0";
var dec = Convert.ToInt32(hex,16); //2016
var oct = Convert.ToString(dec,8); //3740
//Octal to Hex
var dec2 = Convert.ToInt32(oct, 8); //2016
var hex2 = dec2.ToString("X"); //7E0

c.) Bin

//Hex to Bin
var hex = "7E0";  
var dec = Convert.ToInt32(hex,16); //2016
var bin = Convert.ToString(dec,2); //0111 1110 0000
//Bin to Hex
var dec2 = Convert.ToInt32(bin, 2); //2016
var hex2 = dec2.ToString("X"); //7E0

2. Dec

a. Octal

//Dec to Octal
var dec = 2016;
var oct = Convert.ToString(dec,8); //3740
//Octal to Dec
var dec2 = Convert.ToInt32(oct, 8); //2016

b. Bin

//Dec to Bin
var dec = 2016;
var bin = Convert.ToString(dec,2); //0111 1110 0000
//Bin to Dec
var dec2 = Convert.ToInt32(bin, 2); //2016


3. Octal

//Oct to Bin
var oct = "3740";
var dec = Convert.ToInt32(oct,8); //2016
var bin = Convert.ToString(dec, 2); //0111 1110 0000
//Bin to Oct
var dec2 = Convert.ToInt32(bin, 2); //2016
var oct2= Convert.ToString(dec2, 8); //3740


Created: 21/04/2016

Share

Happy Reading!

[C# .NET] Convert Between Hexadecimal, Decimal, Octal, Binary With C#
4/ 5
Oleh

Buzz!

Stay updated via email new newsletter

Don't
Use obscene or offensive language.
Personally attack people, their edits, or their comments.
Rant or otherwise harass, abuse, or intimidate others.
Post anything you don't want the world to see. This is a public space.
Infringe copyright.