# CSAPP datalab

This is the writeup for CSAPP datalab

## bitXor

`XOR`

gate can be composed by couple `NAND`

gate. Use legal ops `~ &`

to construct `NAND`

gate to get `XOR`

.

1 | int bitXor(int x, int y) { |

## tmin

$T_{min}$ is `0x80000000 = 0b1000...0`

. Do bit shift on 1 will get the correct result

1 | int tmin(void) { |

## isTmax

$T_{max}$ is `0x700000000 = 0b0111...1`

, which is $T_{min} = T_{max} + 1$. Also, we know that $T_{min} + T_{max} = 0$. So we may use this advantage to solve the puzzle.

1 | int isTmax(int x) { |

## allOddBits

To satisfy the requirement of having all odd bits to be 1, the simplest number is `0xAAAAAAAA = 0b1010...1010`

.

1 | int allOddBits(int x) { |

## negate

Doing two’s complement negation. Use negate operator then add 1.

1 | int negate(int x) { |

## isAsciiDigit

Make sure it range from `0x30 ~ 0x39 (inclusive)`

which means that `(x - 0x30) >= 0 && (0x39 - x) >= 0`

. So implement this into code.

1 | int isAsciiDigit(int x) { |

## conditional

We may use `!!`

to identify if `x`

is not 0. When `x`

is not 0, we should have `y`

side identifier to be `0xfff...f`

and `z`

side to be `0x0`

, and when `x`

is 0 vise versa. Therefore, it only satisfy one side of `|`

operator, other side will be 0.

1 | int conditional(int x, int y, int z) { |

## isLessOrEqual

Solve the problem case by case

1 | int isLessOrEqual(int x, int y) { |

## logicalNeg

There are two number that is same as itself after the negation, $T_{min}$ and 0. But 0 always “positive” (most significant bit is 0).

1 | int logicalNeg(int x) { |

## *howManyBits

I have no idea how to implement this except for stupid enumeration. I find a solution instead.

The solution first flip the sign of the input if it is negative. Then, it doing a binary search on the processed input. **Key here on the binary search is that he shift the input based on what it get.**

1 | int howManyBits(int x) { |

## floatScale2

In floating point part, we are allowed to use `if, while`

those branch and loop, which is much easier than stuffs above.

1 | unsigned floatScale2(unsigned uf) { |

## float Float2Int

1 | int floatFloat2Int(unsigned uf) { |

## floatPower2

1 | unsigned floatPower2(int x) { |