[Console] C# 문자 변환

2011. 8. 4. 12:24C#/Console

1. String -> Hex

1.private int ChangeStringToHex(String source)
2.{
3.return int.Parse(source, System.Globalization.NumberStyles.HexNumber);
4.}

 

2. Hex -> String

1.private String ChangeHexToString(int number)
2.{
3.return Convert.ToString(number, 16).ToUpper().PadLeft(2, '0');
4.}


3. Byte[] -> UInt32

1.private UInt32 ChangeByteToUInt32(byte[] src, int i)
2.{
3.return src[i] + (src[i + 1] << 8) + (src[i + 2] << 16) + (src[i + 3] << 24);;
4.}

상위바이트가 뒤에올경우

1.private UInt32 ChangeByteToUInt32Big(byte[] src, int i)
2.{
3.return src[i + 3] + (src[i + 2] << 8) + (src[i + 1] << 16) + (src[i] << 24);
4.}


4. UInt32 -> Byte[]

01.private void convertUint32ToByte(byte[] dstByte, UInt32 srcUint, int start)
02.{
03.dstByte[3 + start] = (byte)((srcUint & 0xff000000) >> 24);
04.dstByte[2 + start] = (byte)((srcUint & 0x00ff0000) >> 16);
05.dstByte[1 + start] = (byte)((srcUint & 0x0000ff00) >> 8);
06.dstByte[0 + start] = (byte)(srcUint & 0x000000ff);
07.}
08. 
09.// Uint를 Byte 형식으로 변환, Big-Endian
10.private void convertUint32ToByteBig(byte[] dstByte, UInt32 srcUint, int start)
11.{
12.dstByte[0 + start] = (byte)((srcUint & 0xff000000) >> 24);
13.dstByte[1 + start] = (byte)((srcUint & 0x00ff0000) >> 16);
14.dstByte[2 + start] = (byte)((srcUint & 0x0000ff00) >> 8);
15.dstByte[3 + start] = (byte)(srcUint & 0x000000ff);
16.}


5. Byte[] -> String

01.// Byte를 String으로 변환하는 함수
02.// Byte Array를 처음부터 그 길이만큼 변환
03.private String string ChangeByteToString(byte[] src)
04.{
05.// return (new UnicodeEncoding()).GetString(src, 0, src.Length); 포멧미정
06.return UnicodeEncoding.ASCII.GetString(src, 0, src.Length);
07.}
08. 
09.// Byte를 String으로 변환하는 함수
10.// Byte Array중 index위치부터 size만큼 String으로 변환
11.private String ChangeByteToString(byte[] src, int index, int size)
12.{
13.// return (new UnicodeEncoding()).GetString(src, index, size); 포멧미정
14.return UnicodeEncoding.ASCII.GetString(src, index, size);
15.}


6. String -> Byte[]

01.//String를 Byte으로 변환
02.private Byte[] ChangeStringToByte(String src)
03.{
04.return UnicodeEncoding.ASCII.GetBytes(src);
05.}
06. 
07.//String를 Byte으로 변환, 원하는 길이만큼 원하는 위치에
08.// String src에서 sindex부터 slength까지의 String을 dst Byte array에서 bindex부터 쓴다
09.// 만약 성공하면 결과값은 slength값과 일치하게 된다.
10.private int ChangeStringToByte(String src, int sindex, int slength, byte[] dst, int bindex)
11.{
12.return UnicodeEncoding.ASCII.GetBytes(src, sindex, slength, dst, bindex);
13.}

'C# > Console' 카테고리의 다른 글

[Console] 숫자만 입력받기  (0) 2011.09.21
[Console] DllImport  (0) 2011.09.14
[Console 08.23] 완벽한 코드  (0) 2011.08.23
[Console]using 사용법  (0) 2011.06.10
[Console 04.15] 01.데이터 파일 저장  (0) 2011.04.15