본문 바로가기
학부생나부랭이/_zoom

2021_09_27~29)zoom study

by 호상 🐧 2021. 9. 29.

2021-09-27
2021-09-28
2021-09-29

지난번 포스팅과 이번 포스팅 텀이 많이 길었네요 ㅠㅠ

16일 이후 민족 대명절 추석을 새고 돌아왔습니다.

추석 주는 과제가 많진 않았지만 혼자 공부도 안했으니..

이번주 부터 다시 열정🔥 을 불태워야 겠습니다.

 

오늘 포스팅은 3일에 걸쳐 해결한 system - programing 과제를 적으려고 합니다.

 

바로 datalab 입니다만,,

역시 처음 접하는 유형이라 구글링도 열심히 해보고

교수님 강의도 다시 들어보는 등 이해하는데 많은 시간을

쏟았다고 생각합니다. 

 

문제풀이는 주석으로 꼼꼼히 (?) 달아 놓았습니다.

/* 
 * CS:APP Data Lab 
 * 
 * <Please put your name and userid here>
 * // HaSangHo a201802170
 * bits.c - Source file with your solutions to the Lab.
 *          This is the file you will hand in to your instructor.
 *
 * WARNING: Do not include the <stdio.h> header; it confuses the dlc
 * compiler. You can still use printf for debugging without including
 * <stdio.h>, although you might get a compiler warning. In general,
 * it's not good practice to ignore compiler warnings, but in this
 * case it's OK.  
 */

#if 0
/*
 * Instructions to Students:
 *
 * STEP 1: Read the following instructions carefully.
 */

You will provide your solution to the Data Lab by
editing the collection of functions in this source file.

INTEGER CODING RULES:
 
  Replace the "return" statement in each function with one
  or more lines of C code that implements the function. Your code 
  must conform to the following style:
 
  int Funct(arg1, arg2, ...) {
      /* brief description of how your implementation works */
      int var1 = Expr1;
      ...
      int varM = ExprM;

      varJ = ExprJ;
      ...
      varN = ExprN;
      return ExprR;
  }

  Each "Expr" is an expression using ONLY the following:
  1. Integer constants 0 through 255 (0xFF), inclusive. You are
      not allowed to use big constants such as 0xffffffff.
  2. Function arguments and local variables (no global variables).
  3. Unary integer operations ! ~
  4. Binary integer operations & ^ | + << >>
    
  Some of the problems restrict the set of allowed operators even further.
  Each "Expr" may consist of multiple operators. You are not restricted to
  one operator per line.

  You are expressly forbidden to:
  1. Use any control constructs such as if, do, while, for, switch, etc.
  2. Define or use any macros.
  3. Define any additional functions in this file.
  4. Call any functions.
  5. Use any other operations, such as &&, ||, -, or ?:
  6. Use any form of casting.
  7. Use any data type other than int.  This implies that you
     cannot use arrays, structs, or unions.

 
  You may assume that your machine:
  1. Uses 2s complement, 32-bit representations of integers.
  2. Performs right shifts arithmetically.
  3. Has unpredictable behavior when shifting an integer by more
     than the word size.

EXAMPLES OF ACCEPTABLE CODING STYLE:
  /*
   * pow2plus1 - returns 2^x + 1, where 0 <= x <= 31
   */
  int pow2plus1(int x) {
     /* exploit ability of shifts to compute powers of 2 */
     return (1 << x) + 1;
  }

  /*
   * pow2plus4 - returns 2^x + 4, where 0 <= x <= 31
   */
  int pow2plus4(int x) {
     /* exploit ability of shifts to compute powers of 2 */
     int result = (1 << x);
     result += 4;
     return result;
  }

FLOATING POINT CODING RULES

For the problems that require you to implent floating-point operations,
the coding rules are less strict.  You are allowed to use looping and
conditional control.  You are allowed to use both ints and unsigneds.
You can use arbitrary integer and unsigned constants.

You are expressly forbidden to:
  1. Define or use any macros.
  2. Define any additional functions in this file.
  3. Call any functions.
  4. Use any form of casting.
  5. Use any data type other than int or unsigned.  This means that you
     cannot use arrays, structs, or unions.
  6. Use any floating point data types, operations, or constants.


NOTES:
  1. Use the dlc (data lab checker) compiler (described in the handout) to 
     check the legality of your solutions.
  2. Each function has a maximum number of operators (! ~ & ^ | + << >>)
     that you are allowed to use for your implementation of the function. 
     The max operator count is checked by dlc. Note that '=' is not 
     counted; you may use as many of these as you want without penalty.
  3. Use the btest test harness to check your functions for correctness.
  4. Use the BDD checker to formally verify your functions
  5. The maximum number of ops for each function is given in the
     header comment for each function. If there are any inconsistencies 
     between the maximum ops in the writeup and in this file, consider
     this file the authoritative source.

/*
 * STEP 2: Modify the following functions according the coding rules.
 * 
 *   IMPORTANT. TO AVOID GRADING SURPRISES:
 *   1. Use the dlc compiler to check that your solutions conform
 *      to the coding rules.
 *   2. Use the BDD checker to formally verify that your solutions produce 
 *      the correct answers.
 */


#endif
/* Copyright (C) 1991-2020 Free Software Foundation, Inc.
   This file is part of the GNU C Library.
   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <https://www.gnu.org/licenses/>.  */
/* This header is separate from features.h so that the compiler can
   include it implicitly at the start of every compilation.  It must
   not itself include <features.h> or any other header that includes
   <features.h> because the implicit include comes before any feature
   test macros that may be defined in a source file before it first
   explicitly includes a system header.  GCC knows the name of this
   header in order to preinclude it.  */
/* glibc's intent is to support the IEC 559 math functionality, real
   and complex.  If the GCC (4.9 and later) predefined macros
   specifying compiler intent are available, use them to determine
   whether the overall intent is to support these features; otherwise,
   presume an older compiler has intent to support these features and
   define these macros by default.  */
/* wchar_t uses Unicode 10.0.0.  Version 10.0 of the Unicode Standard is
   synchronized with ISO/IEC 10646:2017, fifth edition, plus
   the following additions from Amendment 1 to the fifth edition:
   - 56 emoji characters
   - 285 hentaigana
   - 3 additional Zanabazar Square characters */
/*
 * isTmax - returns 1 if x is the maximum, two's complement number,
 *     and 0 otherwise 
 *   Legal ops: ! ~ & ^ | +
 *   Max ops: 10
 *   Rating: 1
 */
int isTmax(int x) {
	// x + 1 = 0x80000000
	// x+ (x+1) = 0xFFFFFFFF
	// !(~(x + (x+1))) = 1
	// amd if x = -1 , then !!(~x)를 해서 걸러낸다.
	return !(~(x + (x + 1))) & !!(~x);
}
/* 
 * bitXor - x^y using only ~ and & 
 *   Example: bitXor(4, 5) = 1
 *   Legal ops: ~ &
 *   Max ops: 14
 *   Rating: 1
 */
int bitXor(int x, int y) {
	//demorgan use
	//드모르간 법칙 사용
	//x xor y = 밑에 적은 식
  return (~(x&y)) & (~(~x & ~y)) ;
}
/* 
 * copyLSB - set all bits of result to least significant bit of x
 *   Example: copyLSB(5) = 0xFFFFFFFF, copyLSB(6) = 0x00000000
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 5
 *   Rating: 2
 */
int copyLSB(int x) {
	// LSB 최하위 비트로 복사
	// 왼쪽 끝 비트를 오른쪽 끝까지 밀고
	// 다시 오른쪽 끝으로 민다.
	// right shift arthmetic use
  return ((x << 31) >> 31);
}
/* 
 * float_abs - Return bit-level equivalent of absolute value of f for
 *   floating point argument f.
 *   Both the argument and result are passed as unsigned int's, but
 *   they are to be interpreted as the bit-level representations of
 *   single-precision floating point values.
 *   When argument is NaN, return argument..
 *   Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
 *   Max ops: 10
 *   Rating: 2
 */
unsigned float_abs(unsigned uf) {
	//2 case 로 나눈다.
	//nan 인경우 와 아닌경우
	//nan 인경우
	//exp 가 전부 0인경우 && frac 이1이 하나라도 있는경우
	//이 경우 uf 를 바로 반환한다.
	//nan 이 아닌경우
	//부호가 1이면 0으로 바꿔주기 위해
	//0x7FFFFFFF 를 이용
	//0x7FFFFFFF = ~(1 << 31)
	//이를 통해 sign bit 을 양수로 변환 후 return 해준다.
	if ( ((~(uf << 1)) >> 24 == 0) && (uf << 9 != 0)) {return uf; }
		return uf & (~(1 << 31));

}
/* 
 * bitMask - Generate a mask consisting of all 1's 
 *   lowbit and highbit
 *   Examples: bitMask(5,3) = 0x38
 *   Assume 0 <= lowbit <= 31, and 0 <= highbit <= 31
 *   If lowbit > highbit, then mask should be all 0's
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 16
 *   Rating: 3
 */
int bitMask(int highbit, int lowbit) {
  
	// highbit 와 lowbit 사이의 값을 1로 변환
	// ~0 = 1 인것을 이용한다.
	// 1111 1111 을 highbit 만큼 오른쪽으로 이동
	// bit 자리는 0부터 시작 highbit + 1
	// 1111 1111 를 lowbit 만큼 이동
	// 이동한 두 bit을 exclusive or 을 통해 비트연산
	// lowbit 으로 민 bit 와 다시 & 연산을 진행
    return(((~0 <<  highbit) << 1) ^ ((~0) << lowbit)) & ((~0) << lowbit)  ;
}
/* 
 * rotateRight - Rotate x to the right by n
 *   Can assume that 0 <= n <= 31
 *   Examples: rotateRight(0x87654321,4) = 0x18765432
 *   Legal ops: ~ & ^ | + << >> !
 *   Max ops: 25
 *   Rating: 3 
 */
int rotateRight(int x, int n) {
	//LSB 를 오른쪽으로 이동
	//x 를 두개로 나누고 or 연산을 통해 합쳐준다.
	//이동한 LSB 와 이동한 LSB 를 제외한 나머지
	//나머지
	// ~0 = 1 , LSB 를 n 만큼 오른쪽으로 이동하기 위해선
	// left shift 를 이용한다.
	// 33 - n 만큼 left shift -> 33 - (~n)
	// 그다음 전체를 보수처리
	//x 를 n 만큼 right shift 
	// 이둘을 & 연산하면 나머지를 구할수 있다.
	// 이동한 LSB
	// x 를 33 - n 만큼left shift 
	// 나머지와 이동한 LSB 를 or 연산 한다.
	return (x >> n) & ~(~0 << (33 + (~n))) | (x << ( 33 + (~n))) ;
}
/* 
 * isAsciiDigit - return 1 if 0x30 <= x <= 0x39 (ASCII codes for characters '0' to '9')
 *   Example: isAsciiDigit(0x35) = 1.
 *            isAsciiDigit(0x3a) = 0.
 *            isAsciiDigit(0x05) = 0.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 15
 *   Rating: 3
 */
int isAsciiDigit(int x) {
	// 3개의 case
	// 앞자리가 3일 경우
	// 뒷자리가 0 ~ 9 안에 속할 경우
	// 0x30 일경우
	// check ten
	// 0x3F 의 보수 처리 후 x 와 and 연산을한다
	// 앞의 자리가 0101 에서 1010 으로 바뀌고 and 연산 시 값이 존재한다면
	// 조건 위배
	// check one 
	// 1~ 9 사잇값중 6을 더하면 15를 넘지 않는다.
	// 이를 이용하여 x and 0xF 를 통해 1의 자리를 얻고
	// +6 을 한 수에 0x10 과 and 를 통해 값이 나오면 조건 미부합
	// check thirty
	// 0x30 and x 를 하면0x30 이 나오거나 다른수가 나온다.
	// 이를 exclusive or 0x30 을할때 0이 나오면 x는 0x30 값이 나오면 조건 미부합
	// 위 세 조건 중 하나라도 위배하면 주조건 0을 return
	int check_ten = x & ~0x3F;
	int check_one = ((x&0xF) + 6) & 0x10;
	int check_thirty = (x& 0x30) ^ 0x30;

 	return !(check_one | check_ten | check_thirty); 
}
/* 
 * bang - Compute !x without using !
 *   Examples: bang(3) = 0, bang(0) = 1
 *   Legal ops: ~ & ^ | + << >>
 *   Max ops: 12
 *   Rating: 4 
 */
int bang(int x) {
	// 0 이 아니면 자신과 , 자신의 음수와의 or 연산을 했을때
	// sign bit 가 1 , 0 이면 연산을 해도 0
	// 왜냐하면 ㅌ | ~x+! 을 하면 음수 + 양수 앞자리는 1 이된다. 
	// 31 을 shift  한 결과는 0 이 아닌경우 1111 1111 ,
	//0인 경우 0이 되므로 여기 1을 더한 결과를 출력
 return( (x | (~x + 1)) >> 31) + 1;
}

 

 

이번 과제 리뷰를 하자면,,,,

 

확실히 비트 연산에 대해 아는게 95% 없다는 것입니다.

(이래서 기초학습이 중요하다....!)

 

막연히 어떻게 하는지만 알고 있었지

실제로 문제로 부딛혀 보니 내가 모르는게 정말 많다는게 느껴 졌습니다.

 

0x7FFFFFFF 부터 시작 하여

여러가지 유형을 생각하고 떠올려보고

모르는게 있다면 강의를 다시 한번 보고

자료도 찾아보고 깃도 찾아보고 하였습니다만,,

 

자신이 만족할 만한 결과에 도달하기까지가 많은 시간이 소요 되었네요..

 

이번 시스템 프로그래밍 과목을 통해

다시 한번 내가 기초가 많이 부족하다고 느껴집니다.

 

단순 코더가 아닌 프로그래머가 되기 위해 노력 합시다...!

 

'학부생나부랭이 > _zoom' 카테고리의 다른 글

2021_09_16)zoom study  (0) 2021.09.16
2021_9_15)zoom study  (0) 2021.09.16
2021_09_14)zoom study  (0) 2021.09.14
2021_09_13)zoom study  (0) 2021.09.13

댓글