Python 에서 16 진수 출력 형식 지정 방법

PythonBeginner
지금 연습하기

소개

Python 은 16 진수를 포함한 다양한 숫자 표현을 다룰 수 있는 다재다능한 프로그래밍 언어입니다. 16 진수는 메모리 주소, 색상 코드, 그리고 바이너리 데이터를 더 간결한 형태로 표현하는 등 컴퓨터 과학에서 널리 사용됩니다. 이 튜토리얼에서는 Python 에서 16 진수 출력을 형식화하는 방법, 기본 개념을 이해하고, 몇 가지 실용적인 응용 분야를 살펴보겠습니다.

16 진수 기본 이해

16 진수 (종종 "hex"로 축약) 는 16 을 기수로 하는 숫자 체계입니다. 10 개의 숫자 (0-9) 를 사용하는 일상적인 10 진수 체계와 달리, 16 진수는 16 개의 고유한 기호, 즉 숫자 0-9 와 문자 A-F 를 사용합니다.

각 16 진수 숫자가 10 진수로 나타내는 값은 다음과 같습니다.

  • 0-9 는 10 진수와 동일하게 유지됩니다.
  • A = 10
  • B = 11
  • C = 12
  • D = 13
  • E = 14
  • F = 15

2 진수에서 16 진수로의 변환

16 진수의 주요 장점 중 하나는 2 진수와의 편리한 관계입니다. 각 16 진수 숫자는 정확히 4 개의 2 진수 숫자 (비트) 를 나타냅니다.

Binary: 0000 = Hex: 0
Binary: 0001 = Hex: 1
...
Binary: 1010 = Hex: A
...
Binary: 1111 = Hex: F

16 진수를 더 잘 이해하기 위해 간단한 Python 스크립트를 만들어 보겠습니다.

  1. LabEx 환경에서 WebIDE (VSCode) 인터페이스를 엽니다.
  2. /home/labex/project 디렉토리에 hex_basics.py라는 새 파일을 만듭니다.
  3. 파일에 다음 코드를 추가합니다.
## Understanding decimal, binary, and hexadecimal conversion
decimal_value = 42

## Convert decimal to binary
binary_value = bin(decimal_value)

## Convert decimal to hexadecimal
hex_value = hex(decimal_value)

## Print all representations
print(f"Decimal: {decimal_value}")
print(f"Binary: {binary_value}")
print(f"Hexadecimal: {hex_value}")

## Let's see a larger number
large_decimal = 255
print(f"\nDecimal: {large_decimal}")
print(f"Binary: {bin(large_decimal)}")
print(f"Hexadecimal: {hex(large_decimal)}")
  1. 파일을 저장합니다.
  2. 스크립트를 실행하려면 WebIDE 에서 터미널을 열고 다음을 실행합니다.
python3 hex_basics.py

다음과 유사한 출력을 볼 수 있습니다.

Decimal: 42
Binary: 0b101010
Hexadecimal: 0x2a

Decimal: 255
Binary: 0b11111111
Hexadecimal: 0xff

Python 은 이러한 숫자에 자동으로 접두사를 추가합니다.

  • 2 진수 값은 0b로 시작합니다.
  • 16 진수 값은 0x로 시작합니다.

이러한 접두사는 코드에서 서로 다른 숫자 체계를 구별하는 데 도움이 됩니다.

Python 에서의 기본적인 16 진수 형식 지정

이제 16 진수의 기본 사항을 이해했으므로 Python 에서 16 진수 값을 형식화하는 방법을 배우겠습니다. Python 은 10 진수와 16 진수 간에 변환하고 필요에 따라 출력을 형식화하는 여러 가지 방법을 제공합니다.

10 진수와 16 진수 간 변환

16 진수 변환 및 형식 지정을 탐색하기 위해 새 파일을 만들어 보겠습니다.

  1. WebIDE 에서 /home/labex/project 디렉토리에 hex_formatting.py라는 새 파일을 만듭니다.
  2. 파일에 다음 코드를 추가합니다.
## Basic hexadecimal conversion examples

## Decimal to hex conversion
decimal_number = 171
hex_from_decimal = hex(decimal_number)
print(f"Decimal {decimal_number} converted to hex: {hex_from_decimal}")

## Hex to decimal conversion
hex_number = "0xAB"
decimal_from_hex = int(hex_number, 16)  ## The 16 specifies base-16 (hexadecimal)
print(f"Hex {hex_number} converted to decimal: {decimal_from_hex}")

## You can also use a hex literal directly in your code
hex_literal = 0xAB  ## This is already an integer in Python
print(f"Hex literal 0xAB as decimal: {hex_literal}")

## Working with binary and hexadecimal
binary_number = 0b10101011  ## Binary literal for 171
print(f"Binary {bin(binary_number)} as hex: {hex(binary_number)}")
  1. 파일을 저장합니다.
  2. 다음을 사용하여 스크립트를 실행합니다.
python3 hex_formatting.py

다음과 유사한 출력을 볼 수 있습니다.

Decimal 171 converted to hex: 0xab
Hex 0xAB converted to decimal: 171
Hex literal 0xAB as decimal: 171
Binary 0b10101011 as hex: 0xab

출력 형식 이해

보시다시피, hex() 함수를 사용하여 10 진수를 16 진수로 변환할 때 Python 은 0x 접두사가 있는 문자열을 반환합니다. 이것은 많은 프로그래밍 언어에서 16 진수 숫자의 표준 표현입니다.

소문자 (a-f) 는 Python 의 16 진수 출력의 기본값입니다. 그러나 응용 프로그램에 따라 대문자 또는 다른 형식이 필요할 수 있습니다.

몇 가지 기본 형식 지정 옵션을 탐색하기 위해 스크립트를 수정해 보겠습니다.

  1. hex_formatting.py 파일에 다음 코드를 추가합니다.
## Controlling the case (uppercase/lowercase)
decimal_value = 171

## Default (lowercase)
hex_lowercase = hex(decimal_value)
print(f"\nDefault hex (lowercase): {hex_lowercase}")

## Using string methods to convert to uppercase
hex_uppercase = hex(decimal_value).upper()
print(f"Hex in uppercase: {hex_uppercase}")

## Removing the 0x prefix
hex_no_prefix = hex(decimal_value)[2:]  ## Slicing the string to remove first 2 chars
print(f"Hex without 0x prefix: {hex_no_prefix}")

## Adding padding for consistent width (2 digits with leading zeros)
hex_padded = f"{decimal_value:02x}"  ## Format specifier for 2-digit hex
print(f"Hex padded to 2 digits: {hex_padded}")

## 4-digit hex with leading zeros
hex_padded_4 = f"{decimal_value:04x}"
print(f"Hex padded to 4 digits: {hex_padded_4}")
  1. 파일을 저장합니다.
  2. 스크립트를 다시 실행합니다.
python3 hex_formatting.py

새로운 출력 섹션은 다음과 같이 표시됩니다.

Default hex (lowercase): 0xab
Hex in uppercase: 0XAB
Hex without 0x prefix: ab
Hex padded to 2 digits: ab
Hex padded to 4 digits: 00ab

이것은 Python 에서 16 진수 출력 형식을 조작하는 몇 가지 간단한 방법을 보여줍니다. 다음 단계에서는 더 고급 형식 지정 옵션을 살펴보겠습니다.

고급 16 진수 형식 지정 기술

이제 16 진수 변환 및 간단한 형식 지정의 기본 사항을 이해했으므로 더 고급 형식 지정 기술을 살펴보겠습니다. Python 은 16 진수 값에 적용할 수 있는 강력한 문자열 형식 지정 기능을 제공합니다.

문자열 형식 지정 메서드 사용

다양한 형식 지정 옵션을 탐색하기 위해 새 파일을 만들어 보겠습니다.

  1. WebIDE 에서 /home/labex/project 디렉토리에 advanced_hex_formatting.py라는 새 파일을 만듭니다.
  2. 파일에 다음 코드를 추가합니다.
## Advanced hexadecimal formatting techniques in Python

decimal_value = 171  ## This will be our example number throughout

print("Different ways to format hexadecimal output in Python:")
print("-" * 50)

## 1. Using format() function
print("\n1. Using the format() function:")
## Basic format (lowercase, no prefix)
print(f"Basic format: {format(decimal_value, 'x')}")
## Uppercase format
print(f"Uppercase: {format(decimal_value, 'X')}")
## With 0x prefix
print(f"With 0x prefix: {format(decimal_value, '#x')}")
## With 0X prefix and uppercase
print(f"With 0X prefix and uppercase: {format(decimal_value, '#X')}")
## Padding to 4 digits
print(f"Padded to 4 digits: {format(decimal_value, '04x')}")
## Padding with spaces
print(f"Padded with spaces: {format(decimal_value, '6x')}")

## 2. Using f-strings (Python 3.6+)
print("\n2. Using f-strings:")
## Basic hex
print(f"Basic format: {decimal_value:x}")
## Uppercase
print(f"Uppercase: {decimal_value:X}")
## With 0x prefix
print(f"With 0x prefix: {decimal_value:#x}")
## With 0X prefix and uppercase
print(f"With 0X prefix and uppercase: {decimal_value:#X}")
## Padding to 4 digits with zeros
print(f"Padded to 4 digits: {decimal_value:04x}")
## Centered in a 10-character field
print(f"Centered: {decimal_value:^10x}")

## 3. Using the str.format() method
print("\n3. Using str.format() method:")
## Basic format
print("Basic format: {:x}".format(decimal_value))
## Uppercase with 0X prefix
print("Uppercase with prefix: {:#X}".format(decimal_value))
## Padding with different align options
print("Right-aligned in 6 spaces: {:>6x}".format(decimal_value))
print("Left-aligned in 6 spaces: {:<6x}".format(decimal_value))
  1. 파일을 저장합니다.
  2. 스크립트를 실행합니다.
python3 advanced_hex_formatting.py

출력은 다양한 16 진수 형식 지정 옵션을 표시합니다.

Different ways to format hexadecimal output in Python:
--------------------------------------------------

1. Using the format() function:
Basic format: ab
Uppercase: AB
With 0x prefix: 0xab
With 0X prefix and uppercase: 0XAB
Padded to 4 digits: 00ab
Padded with spaces:     ab

2. Using f-strings:
Basic format: ab
Uppercase: AB
With 0x prefix: 0xab
With 0X prefix and uppercase: 0XAB
Padded to 4 digits: 00ab
Centered:     ab

3. Using str.format() method:
Basic format: ab
Uppercase with prefix: 0XAB
Right-aligned in 6 spaces:     ab
Left-aligned in 6 spaces: ab

바이트 배열 16 진수 덤프 생성

16 진수 형식 지정의 일반적인 응용 프로그램 중 하나는 바이너리 데이터의 16 진수 덤프를 만드는 것입니다. 바이트 배열의 16 진수 덤프를 표시하는 간단한 함수를 만들어 보겠습니다.

  1. advanced_hex_formatting.py 파일에 다음 코드를 추가합니다.
## 4. Creating a hex dump of binary data
print("\n4. Creating a hex dump of binary data:")

def hex_dump(data, bytes_per_line=16):
    """Display a hex dump of binary data with both hex and ASCII representation."""
    result = []

    for i in range(0, len(data), bytes_per_line):
        chunk = data[i:i+bytes_per_line]
        ## Create the hex representation
        hex_repr = ' '.join(f'{b:02x}' for b in chunk)

        ## Create the ASCII representation (printable chars only)
        ascii_repr = ''.join(chr(b) if 32 <= b <= 126 else '.' for b in chunk)

        ## Format the line with address, hex values, and ASCII representation
        line = f"{i:04x}: {hex_repr:<{bytes_per_line*3}} {ascii_repr}"
        result.append(line)

    return '\n'.join(result)

## Example: Creating some sample binary data
sample_data = bytes([
    0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21,  ## "Hello World!"
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,  ## Control characters
    0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x7F                                ## More control chars
])

## Print the hex dump
print(hex_dump(sample_data))
  1. 파일을 저장합니다.
  2. 스크립트를 다시 실행합니다.
python3 advanced_hex_formatting.py

출력의 새 섹션은 바이트 배열의 16 진수 덤프를 표시합니다.

4. Creating a hex dump of binary data:
0000: 48 65 6c 6c 6f 20 57 6f 72 6c 64 21 00 01 02 03 Hello World!....
0010: 04 05 06 07 08 09 0a 0b 1a 1b 1c 1d 1e 1f 7f    ...............

이 16 진수 덤프 형식은 바이너리 데이터, 네트워크 패킷 또는 파일 내용을 검사할 때 일반적으로 사용됩니다. 각 줄은 다음을 보여줍니다.

  • 16 진수 주소/오프셋
  • 각 바이트의 16 진수 값
  • ASCII 표현 (인쇄 가능한 문자는 직접 표시되고 인쇄할 수 없는 문자는 점으로 표시됨)

이러한 고급 형식 지정 기술은 Python 프로그램에서 16 진수 데이터를 처리하기 위한 강력한 도구를 제공합니다.

Python 에서 16 진수의 실용적인 응용

이제 Python 에서 16 진수 값을 형식화하는 방법을 배웠으므로 16 진수 형식화가 특히 유용한 몇 가지 실용적인 응용 프로그램을 살펴보겠습니다.

1. RGB 색상 값 작업

16 진수는 웹 개발 및 그래픽 프로그래밍에서 색상을 나타내는 데 일반적으로 사용됩니다. RGB 색상 값은 #RRGGBB 형식의 16 진수 삼중항으로 표현할 수 있습니다.

16 진수를 사용하여 색상으로 작업하는 방법을 보여주는 스크립트를 만들어 보겠습니다.

  1. WebIDE 에서 /home/labex/project 디렉토리에 hex_color_converter.py라는 새 파일을 만듭니다.
  2. 파일에 다음 코드를 추가합니다.
## Working with RGB color values using hexadecimal

def rgb_to_hex(r, g, b):
    """Convert RGB values to a hexadecimal color string."""
    ## Ensure values are within valid range (0-255)
    r = max(0, min(255, r))
    g = max(0, min(255, g))
    b = max(0, min(255, b))

    ## Create hex string with ## prefix
    return f"#{r:02x}{g:02x}{b:02x}"

def hex_to_rgb(hex_color):
    """Convert a hexadecimal color string to RGB values."""
    ## Remove ## if present
    hex_color = hex_color.lstrip('#')

    ## Convert hex to decimal
    if len(hex_color) == 3:  ## Handle shorthand hex (#RGB)
        r = int(hex_color[0] + hex_color[0], 16)
        g = int(hex_color[1] + hex_color[1], 16)
        b = int(hex_color[2] + hex_color[2], 16)
    else:  ## Handle full hex (#RRGGBB)
        r = int(hex_color[0:2], 16)
        g = int(hex_color[2:4], 16)
        b = int(hex_color[4:6], 16)

    return (r, g, b)

## Example usage
print("RGB to Hex Color Conversion Examples:")
print("-" * 40)

## Common colors
colors = [
    (255, 0, 0),      ## Red
    (0, 255, 0),      ## Green
    (0, 0, 255),      ## Blue
    (255, 255, 0),    ## Yellow
    (255, 0, 255),    ## Magenta
    (0, 255, 255),    ## Cyan
    (255, 255, 255),  ## White
    (0, 0, 0)         ## Black
]

## Convert and display each color
for rgb in colors:
    hex_color = rgb_to_hex(*rgb)
    print(f"RGB: {rgb} → Hex: {hex_color}")

print("\nHex to RGB Color Conversion Examples:")
print("-" * 40)

## List of hex colors to convert
hex_colors = ["#ff0000", "#00ff00", "#0000ff", "#ff0", "#f0f", "#0ff"]

for hex_color in hex_colors:
    rgb = hex_to_rgb(hex_color)
    print(f"Hex: {hex_color} → RGB: {rgb}")

## Color blending example
print("\nColor Blending Example:")
print("-" * 40)

def blend_colors(color1, color2, ratio=0.5):
    """Blend two colors according to the given ratio."""
    r1, g1, b1 = hex_to_rgb(color1)
    r2, g2, b2 = hex_to_rgb(color2)

    r = int(r1 * (1 - ratio) + r2 * ratio)
    g = int(g1 * (1 - ratio) + g2 * ratio)
    b = int(b1 * (1 - ratio) + b2 * ratio)

    return rgb_to_hex(r, g, b)

## Blend red and blue with different ratios
red = "#ff0000"
blue = "#0000ff"

print(f"Color 1: {red} (Red)")
print(f"Color 2: {blue} (Blue)")

for i in range(0, 11, 2):
    ratio = i / 10
    blended = blend_colors(red, blue, ratio)
    print(f"Blend ratio {ratio:.1f}: {blended}")
  1. 파일을 저장합니다.
  2. 스크립트를 실행합니다.
python3 hex_color_converter.py

출력은 RGB 와 16 진수 색상 형식 간의 변환을 보여줍니다.

RGB to Hex Color Conversion Examples:
----------------------------------------
RGB: (255, 0, 0) → Hex: #ff0000
RGB: (0, 255, 0) → Hex: #00ff00
RGB: (0, 0, 255) → Hex: #0000ff
RGB: (255, 255, 0) → Hex: #ffff00
RGB: (255, 0, 255) → Hex: #ff00ff
RGB: (0, 255, 255) → Hex: #00ffff
RGB: (255, 255, 255) → Hex: #ffffff
RGB: (0, 0, 0) → Hex: #000000

Hex to RGB Color Conversion Examples:
----------------------------------------
Hex: #ff0000 → RGB: (255, 0, 0)
Hex: #00ff00 → RGB: (0, 255, 0)
Hex: #0000ff → RGB: (0, 0, 255)
Hex: #ff0 → RGB: (255, 255, 0)
Hex: #f0f → RGB: (255, 0, 255)
Hex: #0ff → RGB: (0, 255, 255)

Color Blending Example:
----------------------------------------
Color 1: #ff0000 (Red)
Color 2: #0000ff (Blue)
Blend ratio 0.0: #ff0000
Blend ratio 0.2: #cc0033
Blend ratio 0.4: #990066
Blend ratio 0.6: #660099
Blend ratio 0.8: #3300cc
Blend ratio 1.0: #0000ff

2. 바이너리 데이터 및 파일 작업

16 진수는 파일 내용 또는 네트워크 패킷과 같은 바이너리 데이터로 작업할 때 자주 사용됩니다. 간단한 16 진수 파일 뷰어를 만들어 보겠습니다.

  1. WebIDE 에서 /home/labex/project 디렉토리에 hex_file_viewer.py라는 새 파일을 만듭니다.
  2. 파일에 다음 코드를 추가합니다.
## Hexadecimal file viewer

def hex_dump(data, bytes_per_line=16, offset=0):
    """Create a hex dump of binary data."""
    result = []

    for i in range(0, len(data), bytes_per_line):
        chunk = data[i:i+bytes_per_line]
        ## Hex representation
        hex_part = ' '.join(f'{b:02x}' for b in chunk)
        ## ASCII representation
        ascii_part = ''.join(chr(b) if 32 <= b <= 126 else '.' for b in chunk)

        ## Add line to result
        line = f"{offset+i:08x}:  {hex_part:<{bytes_per_line*3}}  |{ascii_part}|"
        result.append(line)

    return '\n'.join(result)

def create_sample_file():
    """Create a sample binary file for demonstration."""
    file_path = "/home/labex/project/sample.bin"

    ## Create some sample data containing:
    ## - Some text
    ## - A range of values from 0-255
    sample_data = bytearray(b"This is a sample binary file.\n")
    sample_data.extend(range(0, 256))

    ## Write to file
    with open(file_path, 'wb') as f:
        f.write(sample_data)

    return file_path

def view_file_as_hex(file_path, max_bytes=256):
    """View a portion of the file as a hex dump."""
    try:
        with open(file_path, 'rb') as f:
            data = f.read(max_bytes)

        print(f"Hex dump of the first {len(data)} bytes of {file_path}:")
        print("-" * 70)
        print(hex_dump(data))

        if max_bytes < 256:
            print(f"\nOnly showing first {max_bytes} bytes. Adjust max_bytes parameter to see more.")

    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
    except Exception as e:
        print(f"Error reading file: {e}")

## Create a sample file and view it
sample_file = create_sample_file()
view_file_as_hex(sample_file, 128)

## Information about the "hex" command in Linux
print("\nFun fact: In Linux, you can use the 'hexdump' or 'xxd' commands")
print("to view binary files in hexadecimal format directly from the terminal.")
  1. 파일을 저장합니다.
  2. 스크립트를 실행합니다.
python3 hex_file_viewer.py

출력은 샘플 바이너리 파일의 16 진수 덤프를 표시합니다.

Hex dump of the first 128 bytes of /home/labex/project/sample.bin:
----------------------------------------------------------------------
00000000:  54 68 69 73 20 69 73 20 61 20 73 61 6d 70 6c 65  |This is a sample|
00000010:  20 62 69 6e 61 72 79 20 66 69 6c 65 2e 0a 00 01  | binary file...|
00000020:  02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11  |................|
00000030:  12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21  |.............. !|
00000040:  22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31  |"#$%&'()*+,-./01|
00000050:  32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 40 41  |23456789:;<=>?@A|
00000060:  42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 50 51  |BCDEFGHIJKLMNOPQ|
00000070:  52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f 60 61  |RSTUVWXYZ[\]^_`a|

Fun fact: In Linux, you can use the 'hexdump' or 'xxd' commands
to view binary files in hexadecimal format directly from the terminal.

이 16 진수 뷰어는 각 바이트의 16 진수 표현과 ASCII 에 해당하는 값을 모두 표시합니다. 이는 바이너리 데이터를 검사하는 데 일반적인 형식입니다.

이러한 실용적인 예는 Python 응용 프로그램에서 16 진수 형식화가 어떻게 유용할 수 있는지 보여줍니다. 색상 조작에서 바이너리 데이터 분석에 이르기까지 16 진수는 다양한 유형의 데이터를 표현하고 작업하는 데 컴팩트하고 효율적인 방법을 제공합니다.

요약

이 튜토리얼에서 다음을 배웠습니다.

  • 16 진수 시스템의 기본 사항과 이진수 및 10 진수와의 관계
  • Python 에서 10 진수와 16 진수 값 간에 변환하는 방법
  • 16 진수 출력을 형식화하는 다양한 기술, 다음을 포함합니다.
    • hex() 함수를 사용한 기본 변환
    • 다양한 접두사, 패딩 및 대소문자 옵션을 사용한 형식 지정
    • 바이너리 데이터의 형식화된 16 진수 덤프 생성
  • Python 에서 16 진수의 실용적인 응용:
    • 웹 및 그래픽 개발에서 RGB 색상 값 작업
    • 16 진수 덤프를 사용하여 바이너리 데이터 및 파일 내용 분석

16 진수 형식 지정을 이해하는 것은 많은 프로그래밍 작업, 특히 저수준 작업, 바이너리 데이터 또는 간결한 표현이 중요한 영역에서 작업할 때 필수적인 기술입니다. 이 튜토리얼에서 배운 기술은 Python 프로그램에서 다양한 데이터 형식을 보다 효율적으로 작업하는 데 도움이 됩니다.

이 분야에 대한 지식을 더 넓히려면 다음을 탐색해 볼 수 있습니다.

  • Python 의 비트 연산
  • 네트워크 프로그래밍 및 패킷 분석
  • 컴퓨터 그래픽 및 이미지 처리
  • 메모리 관리 및 시스템 프로그래밍