Created
June 22, 2018 14:27
-
-
Save beiweiqiang/5b494438a143e01868a77a96f3dbb78b to your computer and use it in GitHub Desktop.
用算术右移, 完成逻辑右移; 用逻辑右移, 完成算术右移
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
/* | |
* CSAPP exercise 2.63 | |
* */ | |
/* | |
* 用算术右移, 完成逻辑右移 | |
* */ | |
unsigned srl(unsigned x, int k); | |
/* | |
* 用逻辑右移, 完成算术右移 | |
* */ | |
int sra(int x, int k); | |
int main() { | |
printf("%x \n", sra(-1, 3)); | |
printf("%x \n", sra(0x40000000, 3)); | |
printf("%x \n", sra(0x80000000, 3)); | |
return 0; | |
} | |
unsigned srl(unsigned x, int k) { | |
unsigned xsra = (int) x >> k; | |
int w = sizeof(int) << 3; | |
int right_value = -1 << (w - k); | |
return xsra & (~right_value); | |
} | |
int sra(int x, int k) { | |
int xsrl = (unsigned) x >> k; | |
int w = sizeof(int) << 3; | |
int mask = -1 << (w - k); | |
int m = 1 << (w - 1); | |
int most_high_bit = m & x; | |
mask &= !most_high_bit - 1; | |
return xsrl | mask; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment