엔지니어가 되고 싶은 공돌이
02. Representation of Integer 본문
2. 1. Integer
1) Signed Integer
- Encoding Positive Number is the same as unsigned numbers.
- Encoding Negative Number is 2’s complement.
2) Numeric Ranges
- Unsigned Values: MIN = 0 [00 … 00], MAX = 2n – 1 [11 … 11].
- Signed Values: MIN = - 2n - 1 [100 … 00], MAX = 2n - 1 - 1 [011 … 11].
3) Sign Extension
- Fill with sign bits.
- if A + B bits -> A bits
Truncate it to lower A bits.
4) Unsigned <-> Signed
- 동일한 비트패턴이 부호가 있는 숫자, 부호가 없는 숫자로 해석됩니다.
The same bit pattern is interpreted as a signed number and a unsigned number.
2. 2. Type Casting
- Constant: 기본적으로 Signed Integer로 간주됩니다.
- Unsigned Integer로 사용하고 싶으면 숫자 뒤에 접미사로 U or u를 붙입니다. ex) 135U.
- 명시적 캐스팅(Explicit Casting): int a, b; unsigned c, d; a = (int) c; .
- 암시적 캐스팅(Implicit Casting): Assignment(할당). Procedure call(함수 호출).
- 만약, Unsigned Value와 Signed Value가 single expression(단일 표현식)에 있거나, Comparison(비교)하게 되면 Signed Value -> Unsigned Value로 변환되어 작업을 수행하게 됩니다.
ex) 0 == 0U (T).
ex) -1 < 0 (T).
ex) -1 < 0U (F).
ex) 2147483647 > (int) 2147483648 (T)
- Unsigned Integer는 디버깅 과정에서 많은 문제(while, if, for문의 조건식에서 주로 발생)를 일으킬 수 있으므로, 되도록이면 Signed Integer를 사용해야 합니다. 제한된 비트내에서 큰 양수를 표현할 때는 Unsigned Integer를 사용합시다.
2. 3. Operations in C
1) Bit-Level Operations: ~, &, |, ^.
- not: ~ ex) ~01102 -> 10012.
- and: & ex) 01102 & 01012 -> 01002.
- or: | ex) 01102 | 01012 -> 01112.
- xor: ^ ex) 01102 ^ 01012 -> 00112.
2) Logic Operations: &&, ||, !.
- Always return 0 or 1.
- &&: and, ||: or, !: not.
- ex) !0x27 -> 0x00(F).
ex) !0x00 -> 0x01(T).
ex) !!0x27 -> 0x01(T).
ex) 0x27 &&( or ||) 0x72 -> 0x01(T).
3) Shift Operations: <<, >>.
- Left Shift: x << y.
x Integer를 y만큼 왼쪽으로 shift합니다.
이 때, 왼쪽의 여분의 비트는 버리고, 오른쪽을 0으로 채웁니다.
- Right Shift: x >> y.
x Integer를 y만큼 오른쪽으로 shift합니다.
이 때, 오른쪽의 여분의 비트는 버리고, Logical Shfit이면 왼쪽을 0으로 채우고, Arithmetic Shift이면 왼쪽을 MSB로 채웁니다.
- ex) -2 >> 2 -> -1.
ex) -2 >> -2 만약, y가 음수이면 양수(+2)로 바꾸어서 컴파일합니다. 컴파일러에 따라서 에러를 내기도 합니다.
4) Arithmetic Operations
- Addition: Maximum bit = Abit일 때, A bit + A bit 연산을 하면 carry가 필요해서 계산결과는 (A + 1) bit가 나
오게 됩니다.
하지만 지정된 자료형에 저장해야하기에 (A + 1) bit에서 carry는 버리고 A bit로 저장합니다.
- Multiplication: Maximum bit = Abit일 때, A bit X A bit 연산을 하면 연산과정에서 2A bit가 필요하지만, 저장을 해야하므로 연산결과에서 상위 A bit를 버리고 하위 A bit로 저장합니다.
shift Operation, Add Operation이 Multiplication Operation보다 빠릅니다.
그래서 C Compiler는 Multiplication이 입력되면 자동으로, Shfit + Add 코드를 생성합니다.
- Division: 컴퓨터에서는 Unsigned 나눗셈 연산은 Logical Shift를 사용합니다. (>>>)
Signed 나눗셈 연산은 Arithmetic Shift를 사용합니다. (>>)
'Computer Science > System Programming' 카테고리의 다른 글
06. Assembly 1: Basic Operations (0) | 2025.02.06 |
---|---|
05. Program and Instruction Set (0) | 2025.02.06 |
04. Byte Ordering (0) | 2025.02.05 |
03. Representation of Floating Points (0) | 2025.02.04 |
01. Digital Systems (0) | 2025.02.03 |