# CS:APP 第 2 章重點提示和練習 (解答) --- ## `2.58` On **big-endian (PowerPC, SPARC, and Internet)**, the 32-bit value x01234567 is stored as four bytes 0x01, 0x23, 0x45, 0x67, while on **little-endian (Intel x86)**, it will be stored in reverse order: ![](https://i.imgur.com/orzleFD.png) 從 LSB / MSB 來看資料排列: ![](https://i.imgur.com/BH8DgK1.png) ```Clike #include <assert.h> #include <stdio.h> typedef unsigned char *byte_ptr; int is_little_endian() { int test_num = 0xff; byte_ptr byte_start = (byte_ptr) &test_num; if (byte_start[0] == 0xff) return 1; return 0; } int main(int argc, char *argv[]) { assert(is_little_endian()); return 0; } ``` Reference: * [Little Endian & Big Endian](http://www.bogotobogo.com/Embedded/Little_endian_big_endian_htons_htonl.php) --- ## `2.66` ```Clike #include <assert.h> #include <stdio.h> /* Generate mask indicating leftmost 1 in x. Assume w=32 * For example, 0xFF00 -> 0x8000, and 0x6000 -> 0x4000. * If x = 0, then return 0 */ int leftmost_one(unsigned x) { /* first, generate a mask that all bits after leftmost one are one * e.g. 0xFF00 -> 0xFFFF, and 0x6000 -> 0x7FFF * If x = 0, get 0 */ x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; /* then, do mask & (~mask >> 1), reserve leftmost bit one * that's we want */ return x & (~x >> 1); } int main(int argc, char *argv[]) { assert(leftmost_one(0xFF00) == 0x8000); assert(leftmost_one(0x6000) == 0x4000); return 0; } ``` ---