티스토리 뷰

C#

C#: 10진수 <-> 16진수 변환 함수

개태형님 2016. 10. 6. 10:00

자주 사용하는 함수임에도 불구하고 항상 쓸때마다 찾아 본다..

 

 

// 16진수로 변환
public string ToHex(int i)
{
	// 대문자 X일 경우 결과 hex값이 대문자로 나온다.
	string hex = i.ToString("x");
	if (hex.Length % 2 != 0)
	{
		hex = "0" + hex;
	}
	return hex;
}

// 10진수로 변환 : Long
public long ToLong(string hex)
{
	return Convert.ToInt64(hex, 16);
}

// 10진수로 변환 : Int
public int ToDec(string hex)
{
	return Convert.ToInt32(hex, 16);
}

// 10진수 -> 16진수
Console.WriteLine(ToHex(10)); // 결과 : 0a

// 16진수 -> 10진수 (Long 형)
Console.WriteLine(ToLong("a")); // 결과 : 10
Console.WriteLine(ToLong("0a")); // 결과 : 10
Console.WriteLine(ToLong("0A")); // 결과 : 10

// 16진수 -> 10진수 (int 형)
Console.WriteLine(ToDec("a")); // 결과 : 10
Console.WriteLine(ToDec("0a")); // 결과 : 10
Console.WriteLine(ToDec("0A")); // 결과 : 10

 

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday