;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "2017-fall-reader.rkt" "csc104")((modname Fri-binary) (compthink-settings #hash((prefix-types? . #f)))) (check-expect #b110101 (+ (* 1 32) ; leftmost bit (* 1 16) (* 0 8) (* 1 4) (* 0 2) (* 1 1) ; rightmost bit )) #d00 #d01 #d02 #d03 ; to get 0 - 15 in binary we need another bit #b0000 ; 0 #b0001 #b0010 #b0011 ; 3 #b0100 #b0101 ; 5 #b0110 ; 6 #b0111 ; 7 #b1000 ; 8 #b1001 #b1010 ; 10 #b1011 #b1100 ; 12 #b1101 #b1110 #b1111 ; 15 (check-expect (even? #b1010) #true) (check-expect (odd? #b0101) #true) ; Conversion: decimal to binary ; Approach #1: look at the rightmost bit first ; Documentation (check-expect (number->bits 7) (list 1 1 1)) (check-expect (number->bits 104) (list 1 1 0 1 0 0 0)) ; Design step (check-expect (number->bits 104) (append (number->bits 52) (list 0))) (check-expect (number->bits 7) (append (number->bits 3) (list 1))) ; Design (check-expect (number->bits 104) (append (number->bits (/ 104 2)) (list 0))) (check-expect (number->bits 7) (append (number->bits (/ (- 7 1) 2)) (list 1))) (define (number->bits n) (cond [(zero? n) (list)] ; so we can stop [(even? n) (append (number->bits (/ n 2)) (list 0))] [else ; (odd? n) (append (number->bits (/ (- n 1) 2)) (list 1))])) ; Following this ourselves ; convert 12 to binary ; is 12 even? yes ; result will end in 0 ; rest of our result will be converting 6 to binary ; is 6 even? yes ; this part of the result will end in 0 ; rest of the result will be converting 3 to binary ; is 3 even? no ; this part of the result will end in 1 ; rest of the result will be converting (3-1)/2 = 1 to binary ; is 1 even? no ; this part of the result will end in 1 ; rest of the result will be converting (1-1)/2 = 0 binary -> done ; since we went right to left, our result is #b1100 ; Approach #2: look for powers of 2 that "fit" ; powers of 2: 1, 2, 4, 8, 16, 32, 64, 128, 256, ... ; 104 = 1 x 64 + 40 ; = 1 x 64 + 1 x 32 + 8 ; = 1 x 64 + 1 x 32 + 0 x 16 + 1 x 8 + 0 x 4 + 0 x 2 + 0 x 1 ; = #b1101000 ; Converting binary to decimal ; start by writing out powers of 2 (1, 2, 4, 8, 16, ...) (check-expect #b10011101 (+ (* 1 1) (* 0 2) (* 1 4) (* 1 8) (* 1 16) (* 0 32) (* 0 64) (* 1 128))) (check-expect #b10011101 (+ (* 1 1) (* 1 4) (* 1 8) (* 1 16) (* 1 128))) (check-expect #b10011101 (+ 1 4 8 16 128)) (check-expect #b10011101 157)