Skip to content

Instantly share code, notes, and snippets.

@beiweiqiang
Last active June 20, 2018 14:20
Show Gist options
  • Save beiweiqiang/83edfea0ec37743b09ba7019a6eaeb28 to your computer and use it in GitHub Desktop.
Save beiweiqiang/83edfea0ec37743b09ba7019a6eaeb28 to your computer and use it in GitHub Desktop.
取得一个 int 类型的最高字节
#include <stdio.h>
int get_msb(int w);
int main() {
int x = 2147483647;
printf("%zd %d\n", sizeof(int), get_msb(x));
return 0;
}
/*
* 取得一个 int 的最高字节
* */
int get_msb(int w) {
// 每个字节 8 位
int shift_val = (sizeof(int) - 1) << 3;
// 右移 24 位
int xright = w >> shift_val;
// 取低 8 位
return xright & 0xff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment