2013년 9월 22일 일요일

Byte Array to Float

[ 설명 ]
- 아래 함수면 왠만한 예외 상황은 해결
- ordering : 송신측의 상황에 따라 변경해서 사용
- IsNaN : Return Value 의 상태에 따라 적당히 사용하면 되겠다
- Math.Round : 아래 함수를 사용 할 때, Return Value 가 무한소수점이 반환 된다면, 다른 쪽에서 여러가지 문제가 발생 할 수 있다. Parameter 로 소수점 자리수를 조절해도 괜찮을 것이다. 일단 급해서 hard coding...

        public static float ByteToFloat(byte[] buf, int startIndex, int nLen, bool ordering)
        {
            try
            {
                float fRtn = 0.00f;

                byte[] tempBuf = new byte[nLen];
                Buffer.BlockCopy(buf, startIndex, tempBuf, 0, nLen);

                if (ordering == false)
                {
                    fRtn = System.BitConverter.ToSingle(tempBuf, 0);
                }
                else
                {
                    fRtn = System.BitConverter.ToSingle(tempBuf.Reverse().ToArray(), tempBuf.Length - sizeof(Single) - 0);
                }

                if (float.IsNaN(fRtn))
                    return (float)0;
                else
                {
                    return (float)Math.Round(fRtn, 2);
                }
            }
            catch
            {
                return (float)0;
            }
        }

댓글 없음: