changing a specific index bit in a binary number in Scheme(Racket) -
i need implement in scheme possibility change specific bit in binary number.
the input : 1.binary number , 2.index of bit change, 3.value set in index.
how can implemented?
here beginning of solution. can see what's need done in remaining case?
; bit-index->number : natural -> natural ; return number in binary notation has 1 in position n ; , has zeros elsewhere (define (bit-index->number n) (expt 2 n)) ; example (displayln (number->string (bit-index->number 3) 2)) ; 1000 ; is-bit-set? : index natural -> boolean ; bit n set in number x? (define (is-bit-set? n x) ; bitwise-and 0 unless bit n set in number x (not (zero? (bitwise-and (bit-index->number n) x)))) (define (set-bit! n x b) (cond [(= b 1) ; need set bit n in x 1 (cond [(is-bit-set? n x) x] ; set [else (+ x (bit-index->number n))])] ; add 2^n [(= b 0) ; <what goes here?> ]))
Comments
Post a Comment