진법변환, 데이터 출력시 자리수 맞추기 같이 헷갈리는 것들은 아래의 참조된 MSDN을 통해
모두 해결되리라 믿어 의심치 않는다 +ㅁ+
자꾸 찾기도 귀찮고 하니까
그냥 msdn 통째로 링크시켜놓고 필요할때마다 불러써야겠다.
연습한다 셈 치고
간단하게 만들어 본 진법변환 프로그램
/* 2, 8, 10, 16진수간 진법 변환 프로그램 *
* http://naaams.blogspot.com/ */
using System;
namespace ChangeNotation
{
public class ChangeNotation
{
int oldNumber = 0;
int tempNumber = 0;
int newNotation = 0;
int shiftValue = 0;
string strResult;
public string StrResult
{
get { return strResult; }
}
char[] charArrayResult;
public char[] CharArrayResult
{
get
{
charArrayResult = strResult.ToCharArray();
return charArrayResult;
}
}
byte[] byteArrayResult;
public byte[] ByteArrayResult
{
get
{
byteArrayResult = System.Text.Encoding.ASCII.GetBytes(strResult);
return byteArrayResult;
}
}
bool isEqualNotation = false;
bool isLastQuotient = false;
bool isDecimal = false;
//oldNotation is only 2, 8, 10, 16
public ChangeNotation(string oldStr, int oldNotation, int newNotation)
{
try
{
oldNumber = tempNumber = Convert.ToInt32(oldStr, oldNotation);
}
catch (ArgumentException e)
{
strResult = "Error: Old & New notation is only integer type value. 2, 8, 10, 16";
return;
}
if (oldNotation == newNotation)
isEqualNotation = true;
if (!isEqualNotation)
{
this.newNotation = newNotation;
switch (newNotation)
{
case 2: shiftValue = 1; break;
case 8: shiftValue = 3; break;
case 10: isDecimal = true; break;
case 16: shiftValue = 4; break;
default: strResult = "Error: Old & New notation is only integer type value. 2, 8, 10, 16"; return;
}
calculrationNotation();
}
else
{
strResult = oldStr;
}
}
private void calculrationNotation()
{
if (isDecimal)
{
strResult = oldNumber.ToString();
return;
}
string tempStringResult = string.Empty;
char[] tempCharArrayResult;
strResult = string.Empty;
for (int i = 0; ; i++)
{
tempStringResult += (tempNumber % newNotation).ToString();
tempNumber = tempNumber >> shiftValue;
if (isLastQuotient)
break;
if (tempNumber / newNotation == 0)
isLastQuotient = true;
}
tempCharArrayResult = tempStringResult.ToCharArray();
for (int i = 0; i < tempCharArrayResult.Length; i++)
{
strResult += tempCharArrayResult[tempCharArrayResult.Length - 1 - i];
}
}
}
}
사용법은
ChangeNotation ch = new ChangeNotation("111111", 8, 10);
string str = ch.StrResult;
char[] chararray = ch.CharArrayResult;
byte[] bytearray = ch.ByteArrayResult;
참 허접하다. -_-ㅋ
0x8030 16진수를 "10000000 00110000" 같이 이진수로 만들고 싶다면!?
아래처럼 +ㅁ+
그냥 써먹을라 그랬더니 8자리씩 끊어지지도 않고 왼쪽에 0도 안붙고 ㅠ
게다가 16진수의 숫자가 크다면.. int형 범위를 넘어가버린다는!!
string hexaStr = "8030";
string binaryStr = string.Empty;
for (int i = 0; i < hexaStr.Length; )
{
ChangeNotation convert = new ChangeNotation(hexaStr.Substring(i, 2), 16, 2);
binaryStr += convert.StrResult.PadLeft(8, '0');
i = i + 2;
}
아래는 형식변환과 관련하여 한번쯤 정독해야 할 msdn. 나부터 읽어야되~ ㅠ참고 :
기본 형식
댓글 없음:
댓글 쓰기