개발입문/자료구조

Bitwise 비트에 관한

haloaround 2018. 1. 28. 23:37

Bitwise 

1. Decimal & Binary  : 10진법과 2진법

2. Integral & Fractional : 정수와 분수

3. Interpretation of Binary Pattern

4. 연산이 쉬운  2's Complement : 여진법 + 1

5. 정확도와 범위를 고려한 n-bit 선택하기



1. Decimal & Binary  : 10진법과 2진법

- 컴퓨터는 Base2, 이진법 체계 Binary

- 8bit 사용 2^8 = 256 가지 숫자를 표현할 수 있다.

signed 는 -128 ~ 127   / unsigned 는 0 ~ 255 

- Base ( 2 or 10 ) 에 따라 다르다.

123 = 10^2 * 1 + 10^1 * 2 + 10^0 * 3

25 = 2^4 * 1 + 2^3 * 1 + 2^0 * 1;




2. Integral & Fractional : 정수와 분수

- 정수, 소수 기본적인 법칙은 똑같다. 2^1, 2^(-1)

10.72 = 정수 Integral + 소수 Fractional

정수 2^3 * 1 + 2^2 * 0 + 2^1 * 1 + 2^0 * 0 +

소수 2^-1 * 1 + 2^-2*0 + 2^-3 * 1 + ...


3. Interpretation of Binary Pattern

0 positive  / 1 negative 은 공통의 법칙


1) Sign-magnitude : sign 빼고 (n-1) bit 계산식이 동일

+37D  =  0  010 0101 B

+0D =  0  000 0000 B

-0D =  1  000 0000 B

-1D =  1  000 0001 B

-37D  =    010 0101 B


2) 1's Complement : Complement 여진법 1 <-> 0 스위칭

+37D  =  0  010 0101 B

+0D =  0  000 0000 B

-0D =  1  111 1111 B

-1D =  1  1111 1110 B           

-37D  =    101  1010 B


3) 2's Complement : Complement 여진법 + 1

+37D  =  0  010 0101 B

+0D =  0  000 0000 B

-1D =  1  1111 1111 B                -2^8 + (2^8-1) = -1

-37D  =    101  1011 B          -2^8 + (2^6+2^4+2^3+2^1+2^0) = -1


-2^8 을 빼고 나머지 숫자를 양수로 더하니까 훨씬 접근하기 쉬운 2's Complement




4. 연산도 쉬운  2's Complement : 여진법 + 1 

- 사실 그냥 더하기만 0/1 더하기만 해도 엄청 직관적인 숫자가 되었다.

65D   0100   0001 B            2^6 + 1

-5D    1 1 1 1   1 0 1 1 B           -2^8 + {(2^8-1) -2^2)}     = -2^0 - 2^2     

60D  0 0 1 1  1 1 0 0 B          2^6 + 1 - 2^0 - 2^2 



5. 정확도와 범위를 고려한 n-bit 선택하기 (precision and range)

- 단, range 8-bit -128 ~ 127 의 범위를 넘어가면 안된다. (연산이 모두 틀어지게된다!)

- 정확하고 빠른 (high-performance) 프로그램을 위해서 적당한 bit 크기를 사용해야 한다.



공부자료: A Tutorial on Data Representation Integers, Floating-point Numbers, and Characters