IT정보공유/C#

C# Byte <-> String, Byte <-> int 상호변환

알지오™ 2020. 3. 24.

프로그래밍을 하다보면 바이트 배열을 스트링으로 바꾼다든가
2바이트 배열을 integer 로 바꾸든가 하는 변환 작업이 필요할 때가 있습니다.

어떻게 바이트배열을 문자로 바꾸는지, 또 바이트 배열을 숫자로 바꾸는 방법
그리고 16진수 변환에 대해 알아보도록 하겠습니다.

 

바이트배열이 ASCII 문자열인 경우
public string ByteArrayToASCII(byte[] byteArray, int startidx, int length)
{
    string sRet = "";
    sRet = Encoding.ASCII.GetString(byteArray, startidx, length);
    return sRet;
}

 

1byte 를 16진수(HEX)로 변환
public string ByteToString(byte oneByte)
{
    return oneByte.ToString("X2");
}

 

바이트배열을 16진수로 변환
public string ByteArrayToString(byte[] byteArray, int startidx, int length)
{
    var hex = new StringBuilder(length * 2);

    for (int i = startidx; i < startidx + length; i++)
    {
        hex.AppendFormat("{0:x2}", byteArray[i]);
    }
    return hex.ToString();
}

 

16비트 Integer인 ushort를 2바이트 배열로 변환하는 방법
private byte[] IntToByte(ushort iValue)
{
    return BitConverter.GetBytes(iValue); 
}

 

2바이트 배열, 또는 4바이트 배열을 Int 로 변환
private int ByteToInt(byte[] data, int lenth)
{
    int iRet = 0;

	switch(lenth)
	{
		case 2:
				iRet = BitConverter.ToUInt16(data, 0);
			break;
		case 4:
				iRet = BitConverter.ToInt32(data, 0);
			break;
	}

    return iRet;
}

 

댓글

💲 추천 글