Microsoft MVP성태의 닷넷 이야기
닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조 [링크 복사], [링크+제목 복사],
조회: 11213
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 8개 있습니다.)
.NET Framework: 539. C# - 부동 소수 계산 왜 이렇게 나오죠? (1)
; https://www.sysnet.pe.kr/2/0/10872

.NET Framework: 540. C# - 부동 소수 계산 왜 이렇게 나오죠? (2)
; https://www.sysnet.pe.kr/2/0/10873

.NET Framework: 608. double 값을 구할 때는 반드시 피연산자를 double로 형변환!
; https://www.sysnet.pe.kr/2/0/11055

개발 환경 구성: 440. C#, C++ - double의 Infinity, NaN 표현 방식
; https://www.sysnet.pe.kr/2/0/11896

기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
; https://www.sysnet.pe.kr/2/0/13212

닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조
; https://www.sysnet.pe.kr/2/0/13617

닷넷: 2258. C# - double (배정도 실수) 저장소의 비트 구조
; https://www.sysnet.pe.kr/2/0/13618

닷넷: 2259. C# - decimal 저장소의 비트 구조
; https://www.sysnet.pe.kr/2/0/13619




C# - float (단정도 실수) 저장소의 비트 구조

예전 글에서,

단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
; https://www.sysnet.pe.kr/2/0/13212

그림으로만 float (단정도 실수), double (배정도 실수)를 설명하고 지나갔는데요, 실제로 코드를 사용해서 이것을 들여다보겠습니다. ^^

우선, 단정도 실수의 분해는 다음의 그림에 따라,

[단정도 실수 - 그림 출처: https://ko.wikipedia.org/wiki/IEEE_754]
single_float_1.png

C# 7.0부터 리터럴에 "_" 밑줄 구분자를 임의의 위치에 추가할 수 있다는 점과 C# 7.2에 추가된 숫자 리터럴의 선행 밑줄을 통해 다음과 같은 표현으로 쉽게 분해할 수 있습니다.

namespace ConsoleApp1;

internal class Program
{
    static unsafe void Main(string[] args)
    {
        float f = -118.625f;

        Console.WriteLine($"{f}: sizeof(float): {sizeof(float)}");
        Console.WriteLine();

        byte* pFloat = (byte*)&f;
        PrintFloatFormat(pFloat);
    }

    private static unsafe void PrintFloatFormat(byte* pFloat)
    {
        uint data = *(uint*)pFloat;

        uint signBitMask  = 0b_1000_0000_0000_0000_0000_0000_0000_0000; // C# 7.2부터 컴파일 가능
        uint exponentMask = 0b_0111_1111_1000_0000_0000_0000_0000_0000;
        uint fractionMask = 0b_0000_0000_0111_1111_1111_1111_1111_1111;

        uint signBit = (data & signBitMask);
        uint exponentBits = (data & exponentMask);
        uint fractionBits = (data & fractionMask);

        Console.WriteLine(Convert.ToString((long)signBit, 2).PadLeft(32, '0').Separator(4, '_'));
        Console.WriteLine(Convert.ToString((long)exponentBits, 2).PadLeft(32, '0').Separator(4, '_'));
        Console.WriteLine(Convert.ToString((long)fractionBits, 2).PadLeft(32, '0').Separator(4, '_'));
    }
}

public static class StringExtension
{
    // ...[생략: 첨부 소스코드 참조]...
}

실행하면 다음과 같은 결과가 나오는데요,

-118.625: sizeof(float): 4

signBit:        1000_0000_0000_0000_0000_0000_0000_0000
exponentBits:   0100_0010_1000_0000_0000_0000_0000_0000
fractionBits:   0000_0000_0110_1101_0100_0000_0000_0000

왜 저런 결과가 나왔는지를 이해하기 위해서는 먼저 IEEE 754 표준에 따라 거치는 정규화 과정을 알아야 합니다. 즉, 위의 경우 "-118.625"는 다음과 같은 정규화 과정을 거칩니다.

2진수 변환)
-118.625 ==> 1110110.101

지수 표현)
1110110.101 ==> 1.110110101 * 26
    지수부: 6
    가수부: 1.110110101

그런데, 이상하군요? ^^ 위에서 지수 6은 2진수로 표현하면 0110인데, 어떻게 코드에서 출력한 exponentBits(100_0010_1), 즉 133이 되었을까요? 그것은 지수부를 표현하는 8비트를 절반 나누어 음의 지수와 양의 지수로 쓰기 때문입니다. 8비트니까, 0 ~ 255까지의 값을 표현할 수 있는데요, 중간인 127을 2의 0승으로 두고 그것보다 작으면 음, 크면 양의 제곱으로 처리를 하는 방식입니다. 따라서 여기서 지수는 6이므로 +127을 해서 133을 exponentBits에 저장한 것이고 그래서 100_0010_1 값이 나온 것입니다.

가수부의 처리도 재미있습니다. 위의 경우 보존해야 할 값은 1110110101이지만 정규화했을 때 언제나 앞자리 하나는 1이므로 (비트를 절약하기 위해) 그 부분은 절삭하고 (1)110110101의 110110101 값만 가수로 저장합니다.

대충 이해가 되시죠? ^^




그렇다면, 위와 같이 분해된 정보로부터 원래의 실숫값을 복원하는 것도 가능합니다.

우선, 가수부의 110110101에서 생략된 가장 상위의 1을 복원시켜줍니다.

1_1011_0101 ==> 11_1011_0101

그다음, 지수부의 133을 원래의 지수로 만들어줍니다. 이를 위해 (반대로) 127을 빼주면 됩니다.

6 = 133 - 127

이렇게 구한 값들을 통해 처음의 float 값으로 복원할 수 있습니다.

1.110110101 * 2E6

==> 1110110.101

10진수로 ==> 118.625

==> sign 비트 적용
-118.625

(118.625의 2진수 값이 실제로 1110110.101인지 진법 계산을 해보면 나오겠지만, 간편하게 온라인 진법 계산기를 사용해 확인할 수도 있습니다.)

이 과정을 코드로 표현하면 대충 다음과 같이 만들 수 있습니다. ^^

{
    bool minus = signBit != 0;
    uint exponents = exponentBits >> 23;

    // 삭제된 1을 복원하고,
    uint fractions = fractionBits | 0b_0000_0000_1000_0000_0000_0000_0000_0000;

    int shift = (int)exponents - 127;

    // (삭제된 1비트의 복원으로 9비트가 아닌) 8비트만 shift 시키면 원래의 가수로 변환
    fractions = fractions << 8;
    string mantissa = Convert.ToString(fractions, 2).TrimEnd('0');
    Console.WriteLine($"{(minus ? "-" : "")}{mantissa} * 2E{shift}");

    mantissa = Convert.ToString(fractions, 2).TrimEnd('0');
    mantissa = MarkDecimalPoint(mantissa, shift);
    Console.WriteLine($"{(minus ? "-" : "")}{mantissa}");

    decimal value = Recomposite(mantissa) * (minus ? -1 : 1);
    Console.WriteLine($"{value}, (float: {(float)value})");
}

private static decimal Recomposite(string mantissa)
{
    int pos = mantissa.IndexOf('.');

    string left = mantissa;
    string right = "";

    if (pos != -1)
    {
        left = mantissa[0..pos];
        right = mantissa[(pos + 1)..];
    }

    decimal integer = parseInteger(left);
    decimal decimalPart = parseDecimalPart(right);

    return integer + decimalPart;
}

private static decimal parseInteger(string left)
{
    decimal result = 0;
    decimal pow2 = 1;

    foreach (char ch in left.Reverse())
    {
        result = result + ((ch == '1') ? 1 : 0) * pow2;
        pow2 *= 2;
    }

    return result;
}

private static decimal parseDecimalPart(string right)
{
    decimal result = 0;
    decimal pow2 = 1m / 2m;

    foreach (char ch in right)
    {
        result = result + ((ch == '1') ? 1 : 0) * pow2;
        pow2 /= 2m;
    }

    return result;
}

private static string MarkDecimalPoint(string mantissa, int shift)
{
    if (shift >= 0)
    {
        shift++;
        mantissa = mantissa.PadRight(shift, '0');
    }
    else
    {
        string decimalPart = new string('0', -shift - 1);
        mantissa = "0." + decimalPart + mantissa;
        return mantissa;
    }

    if (mantissa.Length == shift)
    {
        return mantissa;
    }

    string left = mantissa[0..shift];
    string right = mantissa[shift..];

    return $"{left}.{right}";
}

이전 코드와 합쳐서 실행해 보면 이런 결과를 얻을 수 있습니다.

-118.625 (decimal: -118.625): sizeof(float): 4

signBit:        1000_0000_0000_0000_0000_0000_0000_0000
exponentBits:   0100_0010_1000_0000_0000_0000_0000_0000
fractionBits:   0000_0000_0110_1101_0100_0000_0000_0000

-1110110101 * 2E6
-1110110.101
-118.625, (float: -118.625)

잘 복원이 되었죠? ^^

(첨부 파일은 이 글의 예제 코드를 포함>합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 5/6/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 61  62  63  [64]  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12373정성태10/14/202017870.NET Framework: 952. OpCodes.Box와 관련해 IL 형식으로 직접 코딩 시 유의할 점
12372정성태10/13/202020893.NET Framework: 951. C# 9.0 - (5) 로컬 함수에 특성 지정 가능(Attributes on local functions)파일 다운로드1
12371정성태10/13/202019965개발 환경 구성: 519. Visual Studio의 Ctrl+Shift+U (Edit.MakeUppercase) 단축키가 동작하지 않는 경우
12370정성태10/13/202019534Linux: 33. Linux - nmcli를 이용한 고정 IP 설정
12369정성태10/12/202023106Windows: 176. Raymond Chen이 한글날에 밝히는 윈도우의 한글 자모 분리 현상 [3]
12368정성태10/12/202019817오류 유형: 668. VSIX 확장 빌드 - The "GetDeploymentPathFromVsixManifest" task failed unexpectedly.
12367정성태10/12/202031616오류 유형: 667. Ubuntu - Temporary failure resolving 'kr.archive.ubuntu.com' [2]
12366정성태10/12/202021655.NET Framework: 950. C# 9.0 - (4) 원시 크기 정수(Native ints) [1]파일 다운로드1
12365정성태10/12/202020016.NET Framework: 949. C# 9.0 - (3) 람다 메서드의 매개 변수 무시(Lambda discard parameters)파일 다운로드1
12364정성태10/11/202020807.NET Framework: 948. C# 9.0 - (2) localsinit 플래그 내보내기 무시(Suppress emitting localsinit flag)파일 다운로드1
12363정성태10/11/202022381.NET Framework: 947. C# 9.0 - (1) 대상으로 형식화된 new 식(Target-typed new expressions) [2]파일 다운로드1
12362정성태10/11/202019233VS.NET IDE: 151. Visual Studio 2019에 .NET 5 rc/preview 적용하는 방법
12361정성태10/11/202021512.NET Framework: 946. C# 9.0을 위한 개발 환경 구성
12360정성태10/8/202015836오류 유형: 666. The type or namespace name '...' does not exist in the namespace 'Microsoft.VisualStudio.TestTools' (are you missing an assembly reference?)
12359정성태10/7/202018106오류 유형: 665. Windows - 재부팅 후 iSCSI 연결이 끊기는 문제
12358정성태10/7/202019750오류 유형: 664. Web Deploy 설치 시 "A newer version of Microsoft Web Deploy 3.6 was found on this machine." 오류 [3]
12357정성태10/7/202017240오류 유형: 663. 이벤트 로그 - The storage optimizer couldn't complete retrim on New Volume
12356정성태10/7/202032819오류 유형: 662. ASP.NET Core와 500.19, 500.21 오류 (0x8007000d)
12355정성태10/3/202016166오류 유형: 661. Hyper-V Linux VM의 Internal 유형의 가상 Switch에 대한 IP 연결이 되지 않는 경우
12354정성태10/2/202030290오류 유형: 660. Web Deploy (msdeploy.axd) 실행 시 오류 기록 [1]
12353정성태10/2/202019370개발 환경 구성: 518. 비주얼 스튜디오에서 IIS 웹 서버로 "Web Deploy"를 이용해 배포하는 방법
12352정성태10/2/202021178개발 환경 구성: 517. Hyper-V Internal 네트워크에 NAT을 이용한 인터넷 연결 제공
12351정성태10/2/202018813오류 유형: 659. Nox 실행이 안 되는 경우 - Unable to bind to the underlying transport for ...
12350정성태9/25/202024283Windows: 175. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 [2]파일 다운로드1
12349정성태9/25/202018122Linux: 32. Ubuntu 20.04 - docker를 위한 tcp 바인딩 추가
12348정성태9/25/202018725오류 유형: 658. 리눅스 docker - Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
... 61  62  63  [64]  65  66  67  68  69  70  71  72  73  74  75  ...