# CSAPP 練習 學習指引:https://hackmd.io/s/SJ7V-qikG ### 2.58 ```clike= /*** 撰寫函式 `is_little_endian`,在 Little endian 機器上返回 `1` 反之返回 `0`,應能在任意機器、無論幾位元的架構都適用 //// ex. long MyData=0x12345678 big_endian: 0x12 0x34 0x56 0x78 little_endian: 0x78 0x56 0x34 0x12 在記憶體中: big_endian little_endian 0x0000 0x12 0x78 0x0001 0x34 0x56 0x0002 0x56 0x34 0x0003 0x78 0x12 ***/ #include <stdio.h> int is_little_endian(){ int test_num = 0xff; char *ptr = (char *) &test_num; if(ptr[0] = 0xff) return 1; else return 0; } int main(){ int endian = is_little_endian(); printf("%d", endian); return 0; } ``` TODO: little_endian 和 big_endian 分別是用在哪些場合 ### 2.66 ```clike= /*** 撰寫函式 `leftmost_one`,產生得以找出數值 x 最高位 `1` 的位元遮罩 ***/ #include <stdio.h> int leftmost_one(unsigned x){ //set bits right of the MSB to 1 x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; //set all bit to 0 except the MSB return x & (~x >> 1); } int main(){ unsigned test_num = 0xff; int mask = leftmost_one(test_num); return 0; } ``` ### 2.92 ```clike= /*** 撰寫函式 `float_negate`,給定浮點數 `f`,回傳 `-f`, 倘若 `f` 是 $NaN$,直接回傳 `f`。輸入數值範圍為有效的 2^32^ 個數值 ***/ ``` ### 4.47 ```clike= /*** 以 C 語言指標改寫原本使用陣列表示法的氣泡排序程式碼 // Bubble sort: Array version void bubble_a(long *data, long count){ long i, last; for(last = count-1; last > 0; last--){ for(i = 0; i < last; i++){ if(data[i+1] < data[i]){ // Swap adjacent elements long t = data[i+1]; data[i+1] = data[i]; data[i] = t; } } } } ***/ // Bubble sort: Pointer version void bubble_a(long *data, long count){ long i, last; for(last = count - 1; last > 0; last--){ for(i = 0; i < last; i++){ if( *(data+i+1) < *(data+i)){ // Swap adjacent elements long t = *(data + i + 1); *(data + i + 1) = *(data + i); *(data + i) = t; } } } } int main() { long test_array[7] = { 15, 7, 8, 4, 6, 2, 9}; bubble_a(test_array, 7); int i; for(i =0; i < 7; i++) printf("%ld ", *(test_array + i)); return 0; } ```