본문 바로가기
Programming/C# and .NET

C# REF. Notes - 001 - 16진수 데이터 값을 이진수로 출력하기

by The Programmer 2025. 2. 11.

[ 기본 이미지 ]

 

 

/**

 * C# 언어에서 16진수 데이터 값을 이진수로 출력하는 방법입니다.

 

*/

 

□ 16진수 데이터 값을 이진수로 출력하기

 

// 간단한 참고용이라 그냥.

// 16진수 데이터 값을 이진수로 출력하기

using System;

class Program
{
    static void Main()
    {
        string hexValue = "1A3F"; // 변환할 16진수 값, 문자열 형태로 주어졌을 경우.
        int intValue = Convert.ToInt32(hexValue, 16); // 16진수 문자열을 정수로 변환
        string binaryValue = Convert.ToString(intValue, 2); // 정수를 이진수 문자열로 변환

        Console.WriteLine($"16진수: {hexValue}"); // 16진수 값 출력
        Console.WriteLine($"이진수: {binaryValue}"); // 이진수 값 출력
    }
}

 

 

■ 결과 :

16진수: 1A3F
이진수: 1101000111111
Press any key to continue . . .

 

 

□ 참고 : 명시적 형변환 : 'Convert.ToInt32(hexValue, 16); 

 

더보기

'Convert.ToInt32(hexValue, 16);'는 16진수 문자열을 10진수 정수로 변환하는 코드입니다.
이를 자세히 분석해 보겠습니다.  

1) 'Convert.ToInt32'의 역할
'Convert.ToInt32(string value, int fromBase)' 메서드는 문자열을 정수('int')로 변환하는 역할을 합니다.  
첫 번째 매개변수 'value'는 변환할 문자열입니다. ("1A3F")  
두 번째 매개변수 'fromBase'는 진법을 지정합니다. ('16' → 16진수)  

즉, "1A3F"라는 16진수 문자열을 10진수 정수로 변환하는 과정입니다.  

2) 변환 과정
"1A3F"는 16진수이며, 이를 10진수로 변환하면 다음과 같습니다:  

#16진수 → 10진수 변환

1A3F (16진수) = (1 × 16³) + (A × 16²) + (3 × 16¹) + (F × 16⁰)
              = (1 × 4096) + (10 × 256) + (3 × 16) + (15 × 1)
              = 4096 + 2560 + 48 + 15
              = 6719 (10진수)

따라서 'Convert.ToInt32("1A3F", 16);'의 결과는 'intValue = 6719'가 됩니다.  

3) 예제 코드


// C#
using System;

class Program
{
    static void Main()
    {
        string hexValue = "1A3F";
        int intValue = Convert.ToInt32(hexValue, 16);
        
        Console.WriteLine($"16진수 {hexValue} → 10진수 {intValue}");
    }
}

#출력 결과

16진수 1A3F → 10진수 6719

4) 'Convert.ToInt32'의 특징
'fromBase'에 '2', '8', '10', '16'을 지정할 수 있음  
  - 'Convert.ToInt32("1010", 2);' → 2진수 "1010"을 10진수로 변환 (결과: '10')  
  - 'Convert.ToInt32("77", 8);' → 8진수 "77"을 10진수로 변환 (결과: '63')  
  - 'Convert.ToInt32("123", 10);' → 10진수 그대로 변환 (결과: '123')  
  - 'Convert.ToInt32("FF", 16);' → 16진수 "FF"를 10진수로 변환 (결과: '255')  

예외 발생 가능  
  - '"1G3F"'처럼 잘못된 16진수 값을 입력하면 'FormatException'이 발생합니다.  
  - '"999999999999"'처럼 'int' 범위를 초과하는 값을 입력하면 'OverflowException'이 발생합니다.  

5) 'Convert.ToInt32' 대신 'int.Parse' 사용 가능
'int.Parse'를 사용하여 동일한 변환을 수행할 수도 있습니다.  
// C#
int intValue = int.Parse("1A3F", System.Globalization.NumberStyles.HexNumber);

이 코드도 "1A3F"를 16진수에서 10진수로 변환합니다.  

6) 결론
- 'Convert.ToInt32(hexValue, 16);'는 16진수 문자열을 10진수 정수로 변환하는 메서드입니다.  
- "1A3F"는 10진수로 변환하면 '6719'가 됩니다.  
- 'int.Parse'를 사용하여 동일한 변환을 수행할 수도 있습니다.  

 

 

참고 자료 :

 

자세한 내용은 [Microsoft 공식 문서]
https://learn.microsoft.com/ko-kr/dotnet/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types
.

.

 

 

 

◈ 문제 1 : 다음 코드와 주석을 평가하세요.

 

int int4Bytes = 0xffff; // 16진수 값 직접 주어졌을 경우. 0xffff에서 ffff의 대문자는 직접 테스트해보세요.

// 16진수(Hexadecimal) 하나가 4비트로 표현될 수 있다. 그러므로 여기서 이 값은 2Bytes만 있어도 됨.

short st2Bytes;

 

st2Bytes = (short) int4Bytes

 

Console.WriteLine("int4Bytes := " + int4Bytes); // 잠자리 눈, Pascal. ^.^;

Console.WriteLine("st2Bytes := " + st2Bytes );

 

 

□ '친절한 설명 따위는 필요 없다' 철학을 '대충' 지키고 있습니다만. ^.^;

 

실습용 완전한 코드 :

 

using System;

namespace ConsoleApp_Ex_003
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int int4Bytes = 0xffff; 
            // 16진수 값 직접 주어졌을 경우. 0xffff에서 ffff의 대문자는 직접 테스트해보세요.
            // 16진수(Hexadecimal) 하나가 4비트로 표현될 수 있다.
            // 그러므로 여기서 이 값은 2Bytes만 있어도 됨.
            short st2Bytes;
            st2Bytes = (short)int4Bytes;

            Console.WriteLine("int4Bytes := " + int4Bytes);
            Console.WriteLine("st2Bytes := " + st2Bytes);
        }
    }
}

 

■ 결과 :

 

int4Bytes := 65535
st2Bytes := -1
Press any key to continue . . .

 

 

■ 설명 :

 

코드와 주석의 내용에 대해 대충 분석해 보겠습니다.

1) 코드의 의미
// C#
int int4Bytes = 0xffff;

'0xffff'는 16진수 값으로, 65535(10진수)에 해당합니다.
'int' 타입은 4바이트(32비트)를 사용하므로, 'int4Bytes'는 65535를 저장하는 4바이트 변수입니다.

// C#
short st2Bytes;
st2Bytes = (short) int4Bytes;

'short' 타입은 2바이트(16비트)를 사용합니다.
'int4Bytes'의 값(65535)을 'short'로 명시적 형변환(casting) 하면, 오버플로(Overflow)가 발생할 수 있습니다.
'short'의 최대값은 32767이므로, '65535'를 저장할 수 없습니다.
따라서 'st2Bytes'에는 잘린 값(오버플로 처리된 값)이 저장됩니다.

2) 실행 결과
// C#
Console.WriteLine("int4Bytes := " + int4Bytes);
Console.WriteLine("st2Bytes := " + st2Bytes);

'int4Bytes'는 65535로 출력됩니다.
'st2Bytes'는 오버플로가 발생하여 -1로 출력됩니다.  
(65535를 'short'로 변환하면 비트가 잘려서 -1이 됨)

3) 주석의 타당성
주석에서 "이 값은 2Bytes만 있어도 됨"이라고 되어 있는데, 이는 잘못된 설명입니다.
'0xffff'는 16비트(2바이트)로 표현 가능하지만, 'int' 타입은 4바이트를 사용합니다.
'short' 타입(2바이트)로 변환하면 오버플로가 발생하여 원래 값을 유지할 수 없습니다.

4) 올바른 코드 수정
오버플로를 방지하려면 'ushort' 타입을 사용하는 것이 적절합니다.
// C#
ushort st2Bytes = (ushort) int4Bytes;
Console.WriteLine("st2Bytes := " + st2Bytes);    // 출력: 65535

'ushort'는 2바이트(16비트) 부호 없는 정수이므로, '65535'를 올바르게 저장할 수 있습니다.

5) 결론
코드 자체는 실행 가능하지만, 'short'로 변환할 경우 오버플로가 발생하여 원래 값이 유지되지 않습니다.  
주석에서 "이 값은 2Bytes만 있어도 됨"이라는 설명은 잘못되었습니다.  
'ushort'를 사용하면 65535를 올바르게 저장할 수 있습니다.

 

 

6) 검토용 완전한 코드 

 

using System;

namespace ConsoleApp_Ex_003
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int int4Bytes = 0xffff; 
            // 16진수 값 직접 주어졌을 경우. 0xffff에서 ffff의 대문자는 직접 테스트해보세요.
            // 16진수(Hexadecimal) 하나가 4비트로 표현될 수 있다.
            // 그러므로 여기서 이 값은 2Bytes만 있어도 됨.
            ushort st2Bytes;
            st2Bytes = (ushort)int4Bytes;

            Console.WriteLine("int4Bytes := " + int4Bytes);
            Console.WriteLine("st2Bytes := " + st2Bytes);
        }
    }
}

 

 

 

◈ 문제 2 : 문제 1에 대한 위 설명을 평가하세요.

 

 

■ 설명 : 생략. ^.^;

 

int4Bytes := 65535
st2Bytes := 65535
Press any key to continue . . .

 

 

생각해볼 문제

1) 오버플로우가 발생해도 이에 대한 경고 메시지가 나타나지 않는다. 왜?

2) 오버플로우가 발생해도 프로그램은 실행된다. 어째서?

3) 바이트 크기와 부호 비트에 대해 생각해 볼 것.

4) 왜 -1인가?

 


참고 자료 : Microsoft 공식 문서
1) https://learn.microsoft.com/ko-kr/dotnet/csharp/programming-guide/types/casting-and-type-conversions

2) https://learn.microsoft.com/ko-kr/dotnet/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types

 

 

즐거운 프로그래밍!

^.^