《CSAPP》(第3版)答案(第三章)(一)

P58

#include <stdio.h>
long decode2(long x,long y,long z){
    long tmp = y-z;
    return (tmp*x)^(tmp<<63>>63);
}
int main(){
    printf("%d\n",decode2(114,514,1919));
}

P59

u x u y = ( x + x 63 2 64 ) ( y + y 63 2 64 ) ux \cdot uy = (x + x_{63}2^{64}) \cdot (y + y_{63}2^{64})

u x u y = x y + ( x 63 y + y 63 x ) 2 64 + x 63 y 63 2 128 ux \cdot uy = x \cdot y + (x_{63}y + y_{63}x)2^{64} + x_{63}y_{63}2^{128}

x y = u x u y ( x 63 y + y 63 x ) 2 64 x \cdot y = ux \cdot uy - (x_{63}y + y_{63}x)2^{64}

store_prod:
  movq %rdx, %rax     
  cqto                
  movq %rsi, %rcx     
  sarq $63, %rcx
  imulq %rax, %rcx    
  imulq %rsi, %rdx    
  addq %rdx, %rcx     
  mulq %rsi           
    addq %rcx, %rdx
  movq %rax, (%rdi)   
  movq %rdx, 8(%rdi)  
  ret

P60

#include <stdio.h>
long loop(long x,long n){
    long result = 0;
    long mask;
    for(mask=1;mask!=0;mask<<=n){
        result|=(x&mask);
    }
    return result;
}
int main(){
    long x = 0x11451419;
    long y = 0x19198100;
    printf("%d\n",loop(x,y));
}

A.

val reg
x %rdi
n %esi
result %rax
mask %rdx

B.
result = 0
mask = 1
C.
mask != 0
D.
mask = mask << n

P61

#include <stdio.h>
long cread_alt(long* jp){
    return (!jp?0:*jp);
}
int main(){
    long ass = 114514;
    printf("%d\n",cread_alt(&ass));
}

P62

#include <stdio.h>
typedef enum{MODE_A,MODE_B,MODE_C,MODE_D,MODE_E} mode_t;
long switchAss(long* p1,long* p2,mode_t action){
    long result = 0;
    switch(action){
        case MODE_A:
            result = *p2;
            *p2=*p1;
            break;
        case MODE_B:
            *p1=*p1+*p2;
            result = *p1;
            break;
        case MODE_C:
            *p1=59;
            result = *p2;
            break;
        case MODE_D:
            *p1=*p2;
            result = 27;
            break;
        case MODE_E:
            result = 27;
            break;
        default:
            result = 12;
            break;                    
    }
    return result;
}
int main(){
    int dick = 114514;
    int ass = 1919810;
    printf("%d\n",switchAss(&dick,&ass,MODE_C));
}

P63

#include <stdio.h>
long switch_prob(long x,long n){
    long result = x;
    switch(n){
        case 60:
            //do nothing
        case 62:
            result=x*8;
            break;
        case 63:
            result = x>>3;
            break;
        case 64:
            x=(x<<4)-x;
        case 65:
            x=x*x;
        default:
            result=x+0x4b;
    }
    return result;
}
int main(){
    printf("%d\n",switch_prob(114514,64));
}

P64

  • A
    TYPE D[R][S][T]
    &D[i][j][k] = Xd + L(STi + T*j + k)
  • B
    R = 7
    S = 5
    T = 13

P65

  • A
    %rdx
  • B
    %rax
  • C
    15

P66

4*n+1

发布了113 篇原创文章 · 获赞 73 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/swy_swy_swy/article/details/105120652
今日推荐