Microsoft MVP성태의 닷넷 이야기
닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조 [링크 복사], [링크+제목 복사],
조회: 1059
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13582정성태3/19/20241956Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20242078개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241563닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241966오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20242191닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20242500닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241948닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20242125닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20242016닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241913닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241947닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241989닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241945닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241868닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241971닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241925오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241995오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241870닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20242095Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20242067디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20242063오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20242172닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20242177디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20243052오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20242273닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20242079Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...