# 비트연산자의 활용

### 코드

{% code title="보수와 마스크를 사용할 때" %}

```
~(값) & 16진수 FF
```

{% endcode %}

{% code title="진수를 변환할 때" %}

```
(값) 의 이진수/팔진수/십진수/십육진수 값
(값) 의 2진수/8진수/10진수/16진수 값
```

{% endcode %}

{% code title="자릿수를 맞춰 출력할 때" %}

```
(값) 의 이진수/팔진수/십진수/십육진수 값 (숫자)자리로
```

{% endcode %}

***

### 설명

비트 연산 결과를 원하는 진수 형태로 변환해 확인할 수 있습니다.

* &#x20;`의 이진수 값` : 결과를 2진수 문자열로 보여줍니다.

* &#x20;`의 십진수 값` : 결과를 10진수 문자열로 보여줍니다.

* &#x20;`(숫자)자리로` : 앞자리를 0으로 채워 자릿수를 맞춥니다.

* `~` (보수)는 비트를 뒤집어 숫자의 성질을 반대로 만듭니다.

* `& 16진수 FF` (마스크)는 무한히 뻗어 나가는 비트를 딱 8개만 남기고 잘라내는 '절단기' 역할을 합니다.

***

### 주의사항

* `16진수 FF` 같은 마스크를 사용하면 하위 비트만 남길 수 있습니다.
* 자리수 지정 시 부족한 자리는 `0`으로 채워집니다.
* 진수 변환 결과는 계산 검증용으로 함께 제시하면 이해가 쉽습니다.

***

### 파이썬 대응 코드

```
n = (~10) & 0xFF
bin(n)[2:] # 이진수 값
str(n) # 십진수 값
format(n, "08b") # 이진수 8자리
format(25, "03d") # 십진수 3자리
```

***

### 예시

{% code title="예시 코드" %}

```
ㄱ = ~10
ㄴ = ㄱ & 16진수 FF

ㄴ 의 이진수 값 보여주기
ㄴ 의 십진수 값 보여주기
ㄴ 의 이진수 값 10자리로 보여주기
25 의 십진수 값 3자리로 보여주기
```

{% endcode %}

{% code title="예시 코드의 출력" %}

```
# (ㄱ = ~(00001010) = 11110101)
# (ㄴ = 11110101 & 11111111 = 11110101)
11110101 # 11110101
245      # 이진수 11110101은 십진수로 245
0011110101 # 이진수 11110101을 10자리로 보여주기
025
```

{% endcode %}

***

### 검색 키워드

비트연산자, 비트마스크, 보수, 2진수, 8진수, 10진수, 16진수, 진수 변환, 자리 수 채우기


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://codebook.horang.it/readme/undefined-3.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
