본문 바로가기
SoftWare/Visual C#

C# 형변환

by 학수씨 2009. 3. 6.
1. String -> Hex
private int ChangeStringToHex(String source)
{
    return int.Parse(source, System.Globalization.NumberStyles.HexNumber);
}


2. Hex -> String
private String ChangeHexToString(int number)
{
   return Convert.ToString(number, 16).ToUpper().PadLeft(2, '0');
}


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

상위바이트가 뒤에올경우
private UInt32 ChangeByteToUInt32Big(byte[] src, int i)
{
    return src[i + 3] + (src[i + 2] << 8) + (src[i + 1] << 16) + (src[i] << 24);
}


4. UInt32 -> Byte[]
private void convertUint32ToByte(byte[] dstByte, UInt32 srcUint, int start)
 {
     dstByte[3 + start] = (byte)((srcUint & 0xff000000) >> 24);
     dstByte[2 + start] = (byte)((srcUint & 0x00ff0000) >> 16);
     dstByte[1 + start] = (byte)((srcUint & 0x0000ff00) >> 8);
     dstByte[0 + start] = (byte)(srcUint & 0x000000ff);
 }


// Uint를 Byte 형식으로 변환, Big-Endian
private void convertUint32ToByteBig(byte[] dstByte, UInt32 srcUint, int start)
 {
     dstByte[0 + start] = (byte)((srcUint & 0xff000000) >> 24);
     dstByte[1 + start] = (byte)((srcUint & 0x00ff0000) >> 16);
     dstByte[2 + start] = (byte)((srcUint & 0x0000ff00) >> 8);
     dstByte[3 + start] = (byte)(srcUint & 0x000000ff);
 }


5. Byte[] -> String
// Byte를 String으로 변환하는 함수

// Byte Array를 처음부터 그 길이만큼 변환
 private String string ChangeByteToString(byte[] src)
 {
     // return (new UnicodeEncoding()).GetString(src, 0, src.Length); 포멧미정
     return UnicodeEncoding.ASCII.GetString(src, 0, src.Length);
 }

// Byte를 String으로 변환하는 함수
// Byte Array중 index위치부터 size만큼 String으로 변환
 private String ChangeByteToString(byte[] src, int index, int size)
 {
     // return (new UnicodeEncoding()).GetString(src, index, size); 포멧미정
     return UnicodeEncoding.ASCII.GetString(src, index, size);
 }


6. String -> Byte[]
//String를 Byte으로 변환
private Byte[] ChangeStringToByte(String src)
{
    return UnicodeEncoding.ASCII.GetBytes(src);
}

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


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

C# 윈도우메세지 WM_USER MESSAGE 받기  (0) 2009.03.06
C# 대리자 Invoke  (0) 2009.03.06
C# 의 Handle hWND  (0) 2009.03.06
C# ControlArray 사용하기  (0) 2009.03.06
C# 에서 외부 DLL 사용  (0) 2009.03.06

댓글