Tomilla / CS-APP2e

Homework Problem Solution for <Computer Systems - A Programmer's Perspective. 2nd. ed>
http://csapp.cs.cmu.edu/
MIT License
39 stars 15 forks source link

2.61 - d - Prints 1 when the most significant bit = 1 #3

Open dud3 opened 7 years ago

dud3 commented 7 years ago

https://github.com/Tomilla/CS-APP2e/blob/master/Solution/Chapter%202/S2HP_2.61.c#L40

Wasn't it supposed to print 0 if the most significant bit is 1?

Try -10.

dud3 commented 7 years ago

I think the following would be nicer and more explanatory:

int test_option_d1(int x) {

    /*
        if sizeof(int) == 4

        4 - 1 = 3
        3 << 3

        011 << 3 = 011000
        011000 = 16 + 8 = 24 (32 - 8)

        x >> 24
    */
    int shift_val = (sizeof(int) - 1) << 3;

    /*
        E.x: 32bit representation

        int 5
        0000 0000 0000 0000 0000 0000 0000 0101 >> 24
        We get the last byte (eight bits) = 0000 0000

        0000 0000 & 1111 1111 = 0000 0000

        int -5
        1111 1111 1111 1111 1111 1111 1111 1011  >> 24
        We get the last byte (eight bits) = 1111 1111

         1111 1111 & 1111 1111 = 1111 1111
    */

    return !(x >> shift_val);
}
dud3 commented 7 years ago

And also it will work correctly.