ITPub博客

首页 > Linux操作系统 > Linux操作系统 > sra(int x, int k) using srl, srl(unsigned x, int k) using sra

sra(int x, int k) using srl, srl(unsigned x, int k) using sra

原创 Linux操作系统 作者:mscpx 时间:2012-09-02 00:15:17 0 删除 编辑
深入理解计算机系统 2课后练习题 2.63, 用算术右移来完成逻辑右移,及使用逻辑右移完成算术右移。

#include
#include

int sra(int x, int k) {
    int xsrl = (unsigned) x >> k;
    int w = sizeof(int) << 3;
    int m = -1 << (w - k - 1);
    int n = (~((xsrl & m) + m) & m) << 1 ;
    return xsrl |= n ;
}

int srl(unsigned x, int k) {
    int xsra = (int) x >> k;
    int w = sizeof(int) << 3;
  
    int t = 0;   
    printf("strange output  %.8x--%.8x\n", -1 << 32,  -1 << (32 - t)); 
    
    int b = w - k;
    
    return (~(-1 << b)) & xsra; // k = 0, test case fail 

    //return ~ (((-1 << (w-k-1)) & xsra) << 1) & xsra;
}


int main() {
    int w = sizeof(int) << 3;
    int  x1 = -53;
    assert(sra(x1, 2) == x1 >> 2);
    assert(sra(x1, 0) == x1 >> 0);
    assert(sra(x1, w-1) == x1 >> (w-1));

    int x2 = 143;
    assert(sra(x2, 3) == x2 >> 3);
    
    int x3 = -1;
    assert(sra(x3, 2) == x3 >> 3);

    int x4 = 0;
    assert(sra(x4, 20) == x4 >> 20);

    int x5 = 0x7FFFFFFF;
    assert(sra(x5, 20) == x5 >> 20);
    
    unsigned ux1 = 0xFABCDEF0;
    assert(srl(ux1, 10) == ux1 >> 10);
    assert(srl(ux1, 0) == ux1 >> 0);
    assert(srl(ux1, w-1) == ux1 >> (w-1));
  
    unsigned ux2 = 0x7FFFFFFF;
    assert(srl(ux2, 15) == ux2 >> 15);
  
    unsigned ux3 = -1;
    assert(srl(ux3, 20) == ux3 >> 20);
    
    printf("test case passed %.8x\n", ~(-1<<32));
    return 0;
}

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/15742414/viewspace-742452/,如需转载,请注明出处,否则将追究法律责任。

下一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2009-06-01

  • 博文量
    36
  • 访问量
    59897