当前访客身份:游客 [ 登录 | 加入开源中国 ]
当前访客身份: 游客 [ 登录 | 加入开源中国 ]
Yonng Yonng
这个人很懒,啥也没写
博客分类
最新评论
访客统计
  • 4
  • 4
  • 19
  • 188
  • 7210

位级运算的一点随笔

发表于2年前(2012-12-07 20:51)   阅读(624) | 评论(0 0人收藏此文章,
1

1月10日 #长沙# OSC 源创会第32期开始报名


    CSAPP这本书买了也有一段时间了,一直没怎么认真的去看,这几天认认真真的看了几章,以前因为学过汇编,自认为对位级的操作理解到位,以为第2章及第3章应该就那么回事,真正看进去还是有收获,能够以如此简单明了的语言将道理讲得这么明白,不是易事!

    任何一本组成原理的书籍都会详细的讲解数字的表示,讲补码运算的时候也都会说到模运算,该书主要从C语言角度将有符号和无符号的位级操作用简单的几个变换X2X(U2T,T2U,U2B,B2U,T2B,B2T)表达式讲的清晰明了,位级的运算其实是一样的。第1次发现原来符号位可以用负权重来解释(也许是我孤陋寡闻了),以前都是把它当成符号位的意义,而通过取反加1得到他的绝对值。把无符号位级表示的[2w-1-1, 2w-1]区间映射到[-2w-1, –1]正好是将每个值减去2w,那么正好最高位的正权变负权,权重还是2w-1不变,这样解释有它的优点,比如符号位扩展时有多个连续的1时,如8位补码11110011,我们只用去管从符号位往右的连续的1的最右边一个1也即第4位(0~7)表示负权就行了,因为前面-128+64+32+16 = -16,这样该数直接就是-16+3 = -13。

    浮点数的描写用了不多的篇幅将IEEE浮点表示讲了清楚明了,舍入也讲得很清楚,这些并不是什么难以理解的内容,但是作者描述得如此到位还是非学了得的。很多时候我们不知道一个东西并不是它太难理解,而是给我们讲解的人并没有用接触到它的本质,用他认为很清楚的语言给我们讲通了,我们也认为理解了,说到各个细节我们也能了如指掌,但过了不久又忘得差不多了。不清楚它为什么要设计成这个样子跟背书有什么区别!

    这本书有趣的地方就是他是教学的基础上产生的,教学过程中有一些有趣的实验,第2章有个数字实验,用有限的操作符通过位级运算完成某些运算。有些很简单,也有一些需要一些技巧,花了我不少时间完成了这个实验。反正是通过测试了的,肯定是有多种实现的,我的也肯定不是最优的。贴出来 in the hope that it will be useful, but WITHOUT ANY WARRANTY,怎么看着这么眼熟……

/* 
 * CS:APP Data Lab 
 * 
 * <Please put your name and userid here>
 * 
 * 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
/* 
 * bitAnd - x&y using only ~ and | 
 *   Example: bitAnd(6, 5) = 4
 *   Legal ops: ~ |
 *   Max ops: 8
 *   Rating: 1
 */
int bitAnd(int x, int y) {
  /* ~(x & y) == ~x | ~y */
  return ~(~x | ~y);
}


/* 
 * getByte - Extract byte n from word x
 *   Bytes numbered from 0 (LSB) to 3 (MSB)
 *   Examples: getByte(0x12345678,1) = 0x56
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 6
 *   Rating: 2
 */
int getByte(int x, int n) {
  /* shift byte to the lowest and mask */
  return (x >> (n << 3)) & 0xff;

}
/* 
 * logicalShift - shift x to the right by n, using a logical shift
 *   Can assume that 0 <= n <= 31
 *   Examples: logicalShift(0x87654321,4) = 0x08765432
 *   Legal ops: ~ & ^ | + << >>
 *   Max ops: 20
 *   Rating: 3 
 */
int logicalShift(int x, int n) {
  /**/
  int t;
  t = (1 << 31) & x;
  x = x >> n;
  t = (t >> n) << 1;
  t = ~t + 1;			/* -t */
  x = x + t;
  return x;
}
/*
 * bitCount - returns count of number of 1's in word
 *   Examples: bitCount(5) = 2, bitCount(7) = 3
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 40
 *   Rating: 4
 */
int bitCount(int x) {
  int mask1, mask2, mask3;
  int temp;
  int sign = (x >> 31) & 1;
  x = x & ((1 << 31) + ~0);

  temp = (0x55 << 8) | 0x55;
  mask1 = (temp << 16) | temp;

  temp = (0x33 << 8) | 0x33;
  mask2 = (temp << 16) | temp;

  temp = (0x0f << 8) | 0x0f;
  mask3 = (temp << 16) | temp;

  x = (x & mask1) + ((x >> 1) & mask1);
  x = (x & mask2) + ((x >> 2) & mask2);
  x = (x & mask3) + ((x >> 4) & mask3);

  return (((x >> 24) + (x >> 16) + (x >> 8) + x) & 0xff) + sign;
}
/* 
 * bang - Compute !x without using !
 *   Examples: bang(3) = 0, bang(0) = 1
 *   Legal ops: ~ & ^ | + << >>
 *   Max ops: 12
 *   Rating: 4 
 */
int bang(int x) {
  /* high half bits | low half bits*/
  x = (x >> 16) | x;
  x = (x >> 8) | x;
  x = (x >> 4) | x;
  x = (x >> 2) | x;
  x = (x >> 1) | x;
  x = x & 1;
  return x ^ 1;
}
/* 
 * tmin - return minimum two's complement integer 
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 4
 *   Rating: 1
 */
int tmin(void) {
  return (1 << 31);
}
/* 
 * fitsBits - return 1 if x can be represented as an 
 *  n-bit, two's complement integer.
 *   1 <= n <= 32
 *   Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 15
 *   Rating: 2
 */
int fitsBits(int x, int n) {
  /* high 32-n+1 bits are all 0s or 1s */
  x = x >> (n + ~0);	/* x >> n-1 */
  x = x + (x & 1);
  return !x;
}
/* 
 * divpwr2 - Compute x/(2^n), for 0 <= n <= 30
 *  Round toward zero
 *   Examples: divpwr2(15,1) = 7, divpwr2(-33,4) = -2
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 15
 *   Rating: 2
 */
int divpwr2(int x, int n) {
  int sign = (x >> 31) & 1;
  int mask = (1 << n) + ~0;
  int lownbits = x & mask;
  
  return (x >> n) + (((!lownbits) ^ 1) & sign);
}
/* 
 * negate - return -x 
 *   Example: negate(1) = -1.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 5
 *   Rating: 2
 */
int negate(int x) {
  return (~x + 1);
}
/* 
 * isPositive - return 1 if x > 0, return 0 otherwise 
 *   Example: isPositive(-1) = 0.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 8
 *   Rating: 3
 */
int isPositive(int x) {
  int sign = (x >> 31) & 1;
  
  return !sign & !!x;
}
/* 
 * isLessOrEqual - if x <= y  then return 1, else return 0 
 *   Example: isLessOrEqual(4,5) = 1.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 24
 *   Rating: 3
 */
int isLessOrEqual(int x, int y) {
  /* if x and y have the same sign, then y - x isn't overflow,
   * if x and y have different sign, return sign number of x.
   */
  int diff = y + (~x + 1); /* y - x */
  int sgnx = (x >> 31) & 1;
  int sgny = (y >> 31) & 1;
  int sgnd = (diff >> 31) & 1;

  return ((sgnx ^ sgny) & sgnx) + ((sgnx ^ sgny ^ 1) & !sgnd);
}
/*
 * ilog2 - return floor(log base 2 of x), where x > 0
 *   Example: ilog2(16) = 4
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 90
 *   Rating: 4
 */
int ilog2(int x) {
  int byte3 = x >> 24;
  int byte2 = (x >> 16) & 0xff;
  int byte1 = (x >> 8) & 0xff;
  int byte0 = x & 0xff;

  int i3 = !!byte3; /* 0: byte3=0, 1: byte3 > 0 */
  int i2 = i3 | !!byte2;
  int i1 = i2 | !!byte1;
  int i0 = i1 | !!byte0;
  int i = i3 + i2 + i1 + i0 + ~0;
  int highbyte = x >> (i << 3); /* highest byte not equal zero */

  int b7 = (highbyte >> 7) & 1;
  int b6 = (highbyte >> 6) & 1;
  int b5 = (highbyte >> 5) & 1;
  int b4 = (highbyte >> 4) & 1;
  int b3 = (highbyte >> 3) & 1;
  int b2 = (highbyte >> 2) & 1;
  int b1 = (highbyte >> 1) & 1;
  int b0 = highbyte & 1;

  int k7 = b7;
  int k6 = k7 | b6;
  int k5 = k6 | b5;
  int k4 = k5 | b4;
  int k3 = k4 | b3;
  int k2 = k3 | b2;
  int k1 = k2 | b1;
  int k0 = k1 | b0;
  int k = k7 + k6 + k5 + k4 + k3 + k2 + k1 + k0 + ~0;

  return (i << 3) + k;
}
/* 
 * float_neg - Return bit-level equivalent of expression -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_neg(unsigned uf) {
  if ((((uf >> 23) & 0xff) ^ 0xff) || !(uf & ((1 << 23) - 1)))
  	uf ^= (1 << 31);
  return uf;
}
/* 
 * float_i2f - Return bit-level equivalent of expression (float) x
 *   Result is returned as unsigned int, but
 *   it is to be interpreted as the bit-level representation of a
 *   single-precision floating point values.
 *   Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
 *   Max ops: 30
 *   Rating: 4
 */
unsigned float_i2f(int x) {
  unsigned res = x & (1 << 31); /* set sign bit */
  int i;
  int exp = (x >> 31) ? 158 : 0; /* 158 = 31 + 127, INT_MIN or zero */
  int frac = 0;
  int delta;
  int frac_mask;

  if (x << 1) { /* x is neither 0 nor INT_MIN */
  	if (x < 0)
      x = -x;
    i = 30;
    while ( !((x >> i) & 1) ) /* low 31 bits are always have 1(s) */
      i--;
    exp = i + 127;
    x = x << (31 - i);
    frac_mask = (1 << 23) - 1;
    frac = frac_mask & (x >> 8);
    x = x & 0xff;
    delta = x > 128 || ((x == 128) && (frac & 1));
    frac += delta;
    if(frac >> 23) {
      frac &= frac_mask;
      exp += 1;
    }
  }
  res = res | (exp << 23);
  res = res | frac;
  return res;
}
/* 
 * float_twice - Return bit-level equivalent of expression 2*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 representation of
 *   single-precision floating point values.
 *   When argument is NaN, return argument
 *   Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
 *   Max ops: 30
 *   Rating: 4
 */
unsigned float_twice(unsigned uf) {
  /* exp == 255, uf is infinity or NaN, don't need to process */
  unsigned res = uf & (1 << 31); /* sign bit */
  int exp = (uf >> 23) & 0xff;
  int frac = uf & ((1 << 23) - 1);
  if ((exp ^ 0xff)) { /* exp != 255 */
    if (!exp) { 
      /* exp == 0 
       * shift left 1 bit, bit 22(highest bit) can shift to exp.
       */
      frac <<= 1;
    }
    else {
      /* exp != 0 */
      exp++;
      if (exp == 255)
        frac = 0; /* infinity */
    }
  }
  res |= exp << 23;
  res |= frac;

  return res;
}
分享到: 1
声明:OSCHINA 博客文章版权属于作者,受法律保护。未经作者同意不得转载。

评论

Yonng

插入: 表情 开源软件

关闭插入表情