1 / 43

10 주차 학습내용

10 주차 학습내용. Bitwise 연산자란 무엇인가 ? Bitwise 연산자의 종류와 기능 Bitwise 연산의 응용 Enumeration 이란 무엇인가 ? Preprocessor 란 무엇인가 ?. Bitwise 연산자란 무엇인가 ?. Bitwise 연산자 이진수로 표현된 정수형 수식에서 돌아가는 연산자로 시스템에 종속적이다 . 논리 bitwise 연산자와 이동 (shift) bitwise 연산자로 이루어진다 . 논리 연산자 ~ : bitwise complement

shayla
Download Presentation

10 주차 학습내용

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 10주차 학습내용 • Bitwise 연산자란 무엇인가? • Bitwise 연산자의 종류와 기능 • Bitwise 연산의 응용 • Enumeration이란 무엇인가? • Preprocessor란 무엇인가?

  2. Bitwise 연산자란 무엇인가? • Bitwise 연산자 • 이진수로 표현된 정수형 수식에서 돌아가는 연산자로 시스템에 종속적이다. • 논리 bitwise 연산자와 이동(shift) bitwise 연산자로 이루어진다. • 논리 연산자 • ~ : bitwise complement • & : bitwise AND • | : bitwise OR • ^ : bitwise exclusive OR • 이동(shift) 연산자 • << : left shift • >> : right shift • Bitwise 연산자의 이용 범위 • Low-level 연산(system dependent) 및 효율적인 연산시 이용 • 예) image processing, data 압축/복원, …

  3. Bitwise 연산자의 종류와 기능 (~) • ~은 bitwise Complement 또는 1의 보수(one’s complement) 연산자로 불리운다. • 기능 • Unary 연산자로 다른 unary 연산자와 비슷한 우선순위와 결합순서를 갖는다. • 주어진 피연산자의 bit 표현의 각 bit를 1은 0으로 0은 1로 바꾼다. • 예제 int a = 0xFFFF, b = 0x0000, c = 0x00ff; ~a  0000 0000 0000 0000 ~b  1111 1111 1111 1111 ~c  1111 1111 0000 0000 ~(~a)  1111 1111 1111 1111 • 2의 보수 컴퓨터 • 음의 정수를 표현할 때 이 수의 양의 정수의 2의 보수로 표현하는 컴퓨터 • 2의 보수는 1의 보수에 1을 더하여 구한다. • 예제 int a = 0x01, b = 0x00; ~a + 1  1111 1111 1111 1110 + 1  1111 1111 1111 1111  -1 ~b + 1  1111 1111 1111 1111 + 1  0000 0000 0000 0000  0

  4. Bitwise 연산자의 종류와 기능 – ( &, ^, |) • &, ^, |은 bitwise and, bitwise exclusive-or, bitwise inclusive-or 연산자로 각각 불리운다. • 기능 • 이항연산자로 우선순위는 &, ^, |순이고 결합순서는 좌에서 우(left to right)이다. • 이들 연산자는 피연산자로 정수를 취하고 두 피연산자들은 integral promotion 규칙이 적용된다. • &(bitwise and) 연산자는 주어진 피연산자들의 각 대응하는 bit의 값이 모두 1인 경우 1로 그렇지 않은 경우 0이된다. • ^(bitwise exclusive-or) 연산자는 주어진 피연산들의 각 대응하는 bit의 값이 서로 다른 경우 1로 같은 경우 0이 된다. • |(bitwise inclusive-or) 연산자는 주어진 피연산들의 각 대응하은 bit의 값 중 1이 있는 경우 1로 그렇지 않은 경우 0이된다.

  5. Bitwise 연산자의 종류와 기능 – ( &, ^, |) • 예제 int a = 0xFFFF, b = 0x0000, c = 0x00ff, d = 0xff00; a & c  1111 1111 1111 1111 (a) 0000 0000 1111 1111 (c) 0000 0000 1111 1111 c | d  0000 0000 1111 1111 (c) 1111 1111 0000 0000 (d) 1111 1111 1111 1111 a ^ b  1111 1111 1111 1111 (a) 0000 0000 0000 0000 (b) 1111 1111 1111 1111

  6. Bitwise 연산자의 종류와 기능 – ( <<, >>) • <<, >>은 좌측 이동(left shift), 우측 이동(right shift) 연산자로 각각 불리운다. • 기능 • 이항연산자로 우선순위는 두 연산자는 서로 갖고 +, -연산자의 밑에 있고 관계연산자 위에 있으며 결합순서는 좌에서 우(left to right)이다. • 이들 연산자는 피연산자로 정수를 취하고 두 피연산자들은 integral promotion 규칙이 적용된다. • <<(left shift) 연산자는 두 번째 피연산자의 수만큼 첫 번째 피연산자의 bit들을 좌측으로 이동시킨다. Bit이 좌측으로 이동될 때 최하위 bit은 0으로 채워진다. a << 2 • >>(right shift) 연산자는 두 번째 피연산자의 수만큼 첫 번째 피연산자의 bit들을 우측으로 이동시킨다. Bit이 우측으로 이동될 때 첫 번째 연산자가 unsigned 정수이면 최상위 bit은 0으로 채워지고 signed 정수이면 시스템에 따라 0 또는 1이 채워진다. a >> 2 • <<, >> 연산자의 두 번째 피연산자의 값이 음수이거나 첫 번째 피연산자의 bit의 수를 초과한 경우 연산의 결과는 정의되어있지 않다.

  7. Bitwise 연산자의 종류와 기능 – ( <<, >>) • 예제 int c = 0x00ff, d = 0xff00; c << 2  0000 0000 1111 1111 2 0000 0011 1111 1100 c >> 2  0000 0000 1111 1111 2 0000 0000 0011 1111 d << 3  1111 1111 0000 0000 3 1111 1000 0000 0000 d >> 3  1111 1111 0000 0000 3 1111 1111 1110 0000 또는0001 1111 1110 0000

  8. Bitwise 연산의 응용 • 비트레벨 연산의 응용 : packing multiple flags into an int #define READ 1 /* 0000 0001 */ #define WRITE 2 /* 0000 0010 */ #define READ_WRITE 3 /* 0000 0011 */ #define EOF 4 /* 0000 0100 */ #define ERROR 8 /* 0000 1000 */ char status= 0; /* set of flags for I/O status */ /* Turn WRITE flag on */ status = status | WRITE; /* Turn ERROR flag on */ status = status | ERROR; /* Test if READ state */ if(status & READ ) ... /* Turn ERROR flag off */ status = status & ~ERROR; ★ Mask란 변수나 식의 특정 bit들을 추출하거나 수정할 때 사용하는 상수나 변수를 지칭한다.

  9. Bitwise 연산의 응용 - 계속 • packing/unpacking four chars into/from one long int long pack(char a, char b, char c, char d) { long p = a; p = (p << 8) | b; p = (p << 8) | c; p = (p << 8) | d; return p; } char unpack(long p, int k) /* k = 0, 1, 2, or 3*/ { int n = k* 8; /* n = 0, 8, 16, or 32 */ unsigned long mask = 255; /* 0000 0000 0... 0000 1111 1111 */ mask <<= n; return ((p & mask) >> n); }

  10. Enumeration이란 무엇인가? • 열거형(enumeration) 타입 • 유한 집합의 이름을 명명하고 그 집합의 원소(enumerator)들 각각을 식별자로 선언하여 사용하는 방법을 제공하는 사용자 정의 데이터 타입이다. • 열거형의 정의 enum tag_name {enumerator, … }; 예) enum card_type {Kuang, Ten, Five, Zero}; • typedef를 이용하여 구조체에와 비슷하게 열거형 정의를 간단하고 의미있게 재정의할 수 있다. 예) typedef cart_type CARD; • 열거형 변수의 선언 enum car_type card1, card2; CARD *ptr;

  11. Enumeration이란 무엇인가? • enumerator는 정수형의 상수로 디폴트로 첫번째 나오는 enumerator의 값은 0이고 다음에 나오는 enumerator들은 앞의 것보다 1큰 값을 갖는다. 예제의 경우 Kunag은 0, Ten은 1, Five는 2, Zero은 3이다. • 열거형 타입의 변수는 값으로 정의에 존재하는 enumerator만을 가질 수 있다. • 열거형 타입의 정의와 선언 예 enum grade {A = 90, B = 80, C = 70, D = 60, E = 50, F = 50}; enum grade gr1, gr2; enum day {mon = 1, tue, wed, thu, fri, sat, sun} day, day1; typedef enum day day; day day1, day2; enum {mon = 1, tue, wed, thu, fri, sat, sun} day, day1; typedef enum day {mon = 1, tue, wed, thu, fri, sat, sun} day; …

  12. Enumeration의 사용 예 • 주어진 grade를 출력한다. enum grade {A = 90, B = 80, C = 70, D = 60, E = 50, F = 50}; typede enum grade GRADE; void GetGrade(GRADE grade) { switch(grade){ case A: printf(“The grade is A.\n”); break; case B: printf(“The grade is B.\n”); break; case C: printf(“The grade is C.\n”); break; case D: printf(“The grade is D.\n”); break; case E: printf(“The grade is E.\n”); break; case F: printf(“The grade is F.\n”); break; } }

  13. Preprocessor란 무엇인가? • 전처리기(Preprocessor)는 말 그대로 프로그램을 컴파일하기 전에 프로그램에서 전처리기에게 지시한 사항들을 처리하는 일을 수행한다. 이것은 C언어의 파워와 표기 방법의 확장을 위해 사용된다. • 프리프로세서의 기능 • 매크로정의 • 파일삽입기능 (헤더파일등의 삽입을 위해) • 조건부 컴파일 (debugging, portability등을 위해) • 프리프로세서 지시자 • #define : 매크로 정의 • #undef : 정의된 매크로 정의 무효화 • #include : 다른 화일을 삽입 • #if #else #endif • #if #elif #endif 조건부컴파일 • #ifdef #endif • #ifndef #endif • 등등

  14. Preprocessor 지시자 - #define, #undef • #define 및 #undef 지시자 • 용도 : 기호상수 및 매크로 정의 • 사용형식 #define 기호상수 문자열 #define 매크로명(매개변수) 문자열 #undef 매크로명 ☞ 문자열이 너무 길어 다음 줄로 이어질 경우 현재 라인의 끝에 \를 추가하고 다음 줄에 나머지 부분을 이어서 작성할 수 있다. ☞매크로의 경우 첫 번째 매개변수와 왼쪽 가로는 서로 붙어 있어야 한다. • 사용예 (매개변수가 없는 경우) • #define SIZE 80 • #define TEXT unsigned char • TEXT array[SIZE]; • (매크로 확장후) • unsigned char array[80]; ★ 프리프로세서는 기호상수가 정의된 이후에 출현한 모든 기호상수를 대응하는 문자열로 모두 대체한다. 다만 “”안에 문자열은 제외된다.

  15. Preprocessor 지시자 - #define, #undef • 매개변수가 있는 경우 • #define max(x,y) (((x) > (y)) ? (x) : (y)) • e = max(a+b, c+d); • (매크로확장 후) • e = (((a+b) > (c+d)) ? (a+b) : (c+d)); • #define SQARE(x) (x)*(x) • e = SQARE(a+b); • (매크로확장 후) • e = (a+b)*(a+b); • #define SQARE(x) x*x • e = SQARE(a+b); • (매크로확장 후) • e = a+b*a+b;  의도한 결과를 얻을 수 없다.

  16. Preprocessor 지시자 - #define, #undef • 매크로와 함수의 유사성와 차이점 • 유사성 : 반복적으로 사용되는 긴 코드를 간략한 이름으로 호출하여 반복적으로 사용할 수 있다. • 차이점 : 매크로 컴파일시에 확장후 수행 길다 빠르다 없다(에러가능성) 함수 수행시 함수코드로 분기 짧다 느리다 있다 매크로호출 코드길이 수행속도 매개변수의 type

  17. Preprocessor 지시자 - #include • #include 지시자 • 용도 : 다른 원시화일을 삽입 (주로 헤더파일) • 사용형식 #include <파일명> : 지정된 시스템 디렉토리내의 파일 삽입 #include “파일명” : 현재 디렉토리내의 파일 삽입 • 사용 예 #include <stdio.h> #include <math.h> main() { ... printf(“cosine of %f is %f\n”, val, cos(val)); ... }

  18. Preprocessor 지시자 - #if, #ifdef, #ifndef • #if 및 #ifdef #ifndef 지시자 • 용도 : 프로그램의 코드 일부분을 선택적으로 컴파일하는 지시자 • 사용형식 : #elif, #else, #endif와 함께 사용 #if 상수수식 문장1 #else 문장2 #endif #if 상수수식1 문장1 #elif 상수수식2 문장2 .... #else 문장n #endif #ifdef 매크로명 문장1 #else 문장2 #endif #ifndef 매크로명 문장1 #else 문장2 #endif

  19. Preprocessor 지시자 - #if, #ifdef, #ifndef • #if #elif #else #endif의 사용 예 #define US 0 #define UK 1 #define FR 2 #define ACTIVE_CURRENCY US #if ACTIVE_CURRENCY == US char currency[]=“dollar”; #elif ACTIVE_CURRENCY == UK char currency[]=“pound”; #else char currency[]=“franc”; #endif

  20. Preprocessor 지시자 - #if, #ifdef, #ifndef • #ifdef #endif의 사용예 #define DEBUG .... #ifdef DEBUG printf(“Debug : a = %d\n”, a); #endif #define HP9000 #ifdef HP9000 code for HP9000 #elif ifdep SUN_SPARC code for SUN_SPARC #else code for IBM_RS6000 #endif

  21. < 암호화 문제-Bitwise 연산자 사용>(예제 6) 주어진 문자열을 암호화하여 출력하고 반대로 암호화된 것을 복호화하여 출력하는 문제로 각 문자에 대응하는 코드는 테이블로 주어진다. 코드는 길이가 가변이고 이진수로 표현된다. 각 코드는 서로 포함되지 않도록 한다. 이것은 암호화된 것을 원 문자열로 복호화되는 것을 보장하기 위해서 이다. 이때 암호화된 결과들은 바이트 단위로 좌측에서부터 빈곳이 없이 채워진다. 코드 테이블 주어진 문자열: ababac 암호화된 문자열: 10110110 00 2 바이트에 들어감.

  22. Level 1 Pseudo code • 코드 테이블을 사용자로부터 입력 받는다. • 암호화할 문자열을 사용자로부터 입력 받는다. • 암호화할 문자열을 암호화 한다. • 암호화된 결과를 출력 한다. • 암호화된 결과를 복호화 한다. • 복호화된 결과를 출력 한다.

  23. 기능별 구조 주 프로그램 코드 테이블 입력 ReadCodeTable 문자열 암호화 EncryptString 암호화 문자열 출력 WriteBitString Bit문자열 복호화 DecryptBitString

  24. Level 2 Pseudo code program /* 코드 테이블을 사용자로부터 입력 받는다. */ ReadCodeTable() /* 암호화할 문자열을 사용자로부터 입력 받는다. */ Read 암호화할 문자열 /* 암호화할 문자열을 암호화 한다. */ EncryptString() /* 암호화된 결과를 출력 한다. */ WriteBitString() /* 암호화된 결과를 복호화 한다. */ DecryptBitString() /* 복호화된 결과를 출력 한다. */ Write 복호화된 문자열 endprogram

  25. Level 2 Pseudo code (계속) /* 코드 테이블을 사용자로부터 입력 받는다. */ function ReadCodeTable() in : 없음 out : 읽은 코드 테이블 정보 return : 코드의 수 while(더 이상의 코드가 없을 때까지) 코드 정보를 읽는다. endwhile endfunction /* 암호화할 문자열을 사용자로부터 입력 받는다. */ Read 암호화할 문자열

  26. Level 2 Pseudo code (계속) /* 암호화할 문자열을 암호화 한다. */ function EncryptString() in : 암호화할 문자열, 암호화할 문자열의 길이 out : 암호화된 Bit문자열, 암호화된 문자열의 bit수 return : 암호화된 문자열의 bit 수 for i = 1 to 암호화할 문자열의 길이step 1 i번째 문자가 코드 테이블에 있는 위치(position)를 찾는다. if(i번째 문자가 코드 테이블에 존재한다면) 암호화된 문자열에 찾은 코드를 추가한다. endif endfor endfunction /* 암호화된 결과를 출력 한다. */ function WriteBitString() in : 암호화된 문자열, 암호화된 문자열의 bit 수 out : 없음 return : 없음 for i = 1 to 암호화된 문자열의 bit 수step 1 i번째 bit의 2진수 값을 출력한다. endfor endfunction

  27. Level 2 Pseudo code (계속) /* 암호화된 결과를 복호화 한다. */ function DecryptBitString() in : 암호화된 문자열, 암호화된 문자열의 bit 수 out : 복호화된 문자열, 복호화된 문자열의 길이 return : 복호화된 문자열의 길이 for i = 1 to 암호화된 문자열의 bit 수 step 1 i번째 bit을 현재까지 읽어들인 비트열에 추가한다. 비트열이 코드 테이블에 있는 위치(position)을 찾는다. if(비트열이 코드 테이블에 존재한다면) 코드 테이블에 있는 문자를 복호화 문자열에 추가한다. 비트열을 비운다. endif endfor endfunction /* 복호화된 결과를 출력 한다. */ write 복호화된 문자열

  28. 기능별 구조 주 프로그램 코드 테이블 입력 ReadCodeTable 문자열 암호화 EncryptString 암호화 문자열 출력 WriteBitString Bit문자열 복호화 DecryptBitString 코드 테이블에서 알파벳 위치 찾기 SearchAlphabet 암호화 문자열에 코드 추가 AttachCode 코드 테이블에서 코드 위치 찾기 SearchCode

  29. 자료구조 문자, 문자에 대응하는 코드 문자열, 코드 문자열의 길이를 멤버로 갖는 구조체를 구성한다. struct code_data : 각 문자에 대응하는 코드를 유지 alphabet : 문자 code : 문자에 대응되는 코드 문자열 lengthOfCode : 코드 문자열의 길이 endstruct array codeTable(MAX_CODE_NUMBER) : 각 문자에 대응하는 코드를 유지하는 테이블로 code_data 구조체 배열로 MAX_CODE_NUMBER 만큼 사용한다. 암호화를 할 경우 주어진 문자의 코드를 찾는데 사용되고 복호화의 경우 주어진 코드에 대응하는 문자를 찾는데 사용된다.

  30. 자료구조 array bitMask_OR(MAX_BIT_MASK_NUMBER) : 1 바이트의 각 위치에 대한 마스크로 code에 존재하는 1의 값이 암호화된 문자열의 특정 위치에 추가하기위해 필요하다. array bitMask_AND(MAX_BIT_MASK_NUMBER) : 1 바이트의 각 위치에 대한 마스크로 code에 존재하는 0의 값이 암호화된 문자열의 특정 위치에 추가하기위해 필요하다. bitMask[0] = 1000 0000 bitMask[1] = 0100 0000 bitMask[2] = 0010 0000 bitMask[3] = 0001 0000 bitMask[4] = 0000 1000 bitMask[5] = 0000 0100 bitMask[6] = 0000 0010 bitMask[7] = 0000 0001 bitMask_ADN[0] = 0111 1111 bitMask_ADN[1] = 1011 1111 bitMask_ADN[2] = 1101 1111 bitMask_ADN[3] = 1110 1111 bitMask_ADN[4] = 1111 0111 bitMask_ADN[5] = 1111 1011 bitMask_ADN[6] = 1111 1101 bitMask_ADN[7] = 1111 1110

  31. Source code #include <stdio.h> #include <string.h> #define MAX_CODE_LENGTH 16 #define MAX_CODE_NUMBER 32 #define MAX_STRING_LENGTH 1024 #define MAX_BIT_MASK_NUMBER 8 // typedef struct code_tag{ char alphabet; char code[MAX_CODE_LENGTH]; int lengthOfCode; } CODE;

  32. Source code (계속) /* 코드 테이블을 사용자로부터 입력 받는다. */ int ReadCodeTable(CODE codeTable[]); /* 암호화할 문자열을 암호화 한다. */ int EncryptString(char original_String[], int length_Of_Original_String, CODE codeTable[], int cnt_Of_Codes, char encoded_String[]); /* 암호화된 결과를 출력 한다. */ void WriteBitString(char encoded_String[], int cnt_Of_EncodedBits); /* 암호화된 결과를 복호화 한다. */ int DecryptBitString(char encoded_String[], int cnt_Of_EncodedBits, CODE codeTable[], int cnt_Of_Codes, char decoded_String[]); /* 주어진 문자의 코드 테이블에서의 위치를 찾는다. */ int SearchAlphabet(char key, CODE codeTable[], int cnt_Of_Codes); /* 주어진 코드를 암호화된 문자열에 추가한다. */ void AttachCode(char encoded_String[], int cnt_Of_Bits, char code[], int lengthOfCode); /* 주어진 코드의 코드 테이블에서의 위치를 찾는다. */ int SearchCode(char key[], CODE codeTable[], int cnt_Of_Codes);

  33. Source code (계속) char bitMask_OR[MAX_BIT_MASK_NUMBER]; char bitMask_AND[MAX_BIT_MASK_NUMBER]; int main() { int i; char original_String[MAX_STRING_LENGTH]; char encoded_String[MAX_STRING_LENGTH]; char decoded_String[MAX_STRING_LENGTH]; int lengthOfEncodedString, lengthOfDecodedString; int cnt_Of_EncodedBits = 0; CODE codeTable[MAX_CODE_NUMBER]; int cnt_Of_Codes; // 암호화에 사용될 매스크를 만든다. for(i = 0; i < 8; i++){ bitMask_OR[i] = 1 << (7 - i); bitMask_AND[i] = bitMask_OR[i] ^ 0xFF; }

  34. Source code (계속) // 코드 테이블을 사용자로부터 입력 받는다. cnt_Of_Codes = ReadCodeTable(codeTable); // 암호화할 문자열을 입력 받는다. printf("Enter the string for encryption.\n"); scanf("%s", original_String); // 주어진 문자열을 암호화 한다. cnt_Of_EncodedBits = EncryptString(original_String, strlen(original_String), codeTable, cnt_Of_Codes, encoded_String); // 암호화된 결과를 출력한다. printf("The number of an encoded string bits : %d\n", cnt_Of_EncodedBits); lengthOfEncodedString = cnt_Of_EncodedBits/8; if(cnt_Of_EncodedBits%8) lengthOfEncodedString++; printf("The length of an encoded string : %d\n", lengthOfEncodedString);

  35. Source code (계속) // 각 bit 값을 출력한다 WriteBitString(encoded_String, cnt_Of_EncodedBits); // 암호화된 것을 복호화한다. lengthOfDecodedString = DecryptBitString(encoded_String, cnt_Of_EncodedBits, codeTable, cnt_Of_Codes, decoded_String); // 복호화된 결과를 출력한다. printf("Decryption result : %s\n", decoded_String); return 0; }

  36. Source code (계속) /* 코드 테이블을 사용자로부터 입력 받는다. */ int ReadCodeTable(CODE codeTable[]) { int cnt = 0; while(cnt < MAX_CODE_NUMBER && scanf("%c %s", &codeTable[cnt].alphabet, codeTable[cnt].code) == 2){ fflush( stdin ); codeTable[cnt].lengthOfCode = strlen(codeTable[cnt].code); cnt++; }//while }

  37. Source code (계속) /* 암호화할 문자열을 암호화 한다. */ int EncryptString(char original_String[], int length_Of_Original_String, CODE codeTable[], int cnt_Of_Codes, char encoded_String[]) { int i; int pos; int cnt_Of_Bits = 0; // 주어진 문자열을 암호화 한다. for(i = 0; i < length_Of_Original_String; i++){ pos = SearchAlphabet(original_String[i], codeTable, cnt_Of_Codes); if(pos >= 0){ AttachCode(encoded_String, cnt_Of_Bits, codeTable[pos].code, codeTable[pos].lengthOfCode); cnt_Of_Bits += codeTable[pos].lengthOfCode; } else{ printf("%c does not exist in code table!!!\n", original_String[i]); return -1; } }//for return cnt_Of_Bits; }

  38. Source code (계속) /* 암호화된 결과를 출력 한다. */ void WriteBitString(char encoded_String[], int cnt_Of_EncodedBits) { int i; int pos = 0; char a; // 암호화된 문자열의 각 bit에 대하여 for(i = 0; i < cnt_Of_EncodedBits; i++){ // 1 바이트를 모두 출력한 경우 다음 바이트의 값을 얻음 if(i%8 == 0){ putchar(' '); a = encoded_String[pos++]; } // 현재 bit의 값을 출력한다. putchar(((a & bitMask_OR[0]) == 0) ? '0' : '1'); // bit들을 왼쪽으로 1 이동시킨다. a <<= 1; }//for putchar('\n'); }

  39. Source code (계속) /* 암호화된 결과를 복호화 한다. */ int DecryptBitString(char encoded_String[], int cnt_Of_EncodedBits, CODE codeTable[], int cnt_Of_Codes, char decoded_String[]) { int i, index; int pos = 0; int length_of_DecodedString = 0; char code[MAX_CODE_LENGTH] = {'\0'}; char a; // 암호화된 문자열의 각 bit에 대하여 for(i = 0; i < cnt_Of_EncodedBits; i++){ // 1 바이트를 모두 처리한 경우 다음 바이트의 값을 얻음 if(i%8 == 0) a = encoded_String[pos++]; // code에 주어진 비트를 추가한다 if(a & bitMask_OR[0]) strcat(code, "1"); else strcat(code, "0"); // bit들을 왼쪽으로 1 이동시킨다. a <<= 1;

  40. Source code (계속) index = SearchCode(code, codeTable, cnt_Of_Codes); if(index != -1){ // 복호화 문자열에 현재 코드의 문자를 추가한다. decoded_String[length_of_DecodedString] = codeTable[index].alphabet; length_of_DecodedString++; // 다음 코드를 얻기 위하여 코드를 비운다. code[0] = '\0'; } }//for decoded_String[length_of_DecodedString] = '\0'; return length_of_DecodedString; }

  41. Source code (계속) /* 주어진 문자의 코드 테이블에서의 위치를 찾는다. */ int SearchAlphabet(char key, CODE codeTable[], int cnt_Of_Codes) { int i; int index = -1; // tableOfCode에서 주어진 문자가 들어있는 위치(position)를 찾는다. for(i = 0; i < cnt_Of_Codes; i++) if(codeTable[i].alphabet == key){ index = i; break; } return index; }

  42. Source code (계속) /* 주어진 코드의 코드 테이블에서의 위치를 찾는다. */ int SearchCode(char key[], CODE codeTable[], int cnt_Of_Codes) { int i; int index = -1; // tableOfCode에서 주어진 문자가 들어있는 위치(position)를 찾는다. for(i = 0; i < cnt_Of_Codes; i++) if(strcmp(codeTable[i].code, key) == 0){ index = i; break; } return index; }

  43. Source code (계속) /* 주어진 코드를 암호화된 문자열에 추가한다. */ void AttachCode(char encoded_String[], int cnt_Of_Bits, char code[], int lengthOfCode) { int i; int lengthOfEncodedString, lastBitPosition; lengthOfEncodedString = cnt_Of_Bits/8; lastBitPosition = cnt_Of_Bits%8; // code를 encoded_String에 추가한다. for(i = 0; i < lengthOfCode; i++){ if(code[i] == '1') encoded_String[lengthOfEncodedString] |= bitMask_OR[lastBitPosition]; else encoded_String[lengthOfEncodedString] &= bitMask_AND[lastBitPosition]; lastBitPosition++; if(lastBitPosition == 8){ lastBitPosition = 0; lengthOfEncodedString = lengthOfEncodedString + 1; } }//for }

More Related