0
Schemeで、バイナリ番号の特定のビットを変更する可能性を実装する必要があります。Scheme(Racket)の2進数の特定のインデックスビットを変更する
入力は次のとおりです。1.バイナリ番号、2.変更するビットのインデックス、3.そのインデックスに設定する値。
どのように実装できますか?
Schemeで、バイナリ番号の特定のビットを変更する可能性を実装する必要があります。Scheme(Racket)の2進数の特定のインデックスビットを変更する
入力は次のとおりです。1.バイナリ番号、2.変更するビットのインデックス、3.そのインデックスに設定する値。
どのように実装できますか?
(define (set-bit value index n)
(let ([mask (arithmetic-shift 1 index)])
(cond [(= value 0) (bitwise-and (bitwise-not mask) n)]
[(= value 1) (bitwise-ior mask n)])))
ここでは解決策の始まりです。残りのケースで何が必要なのか分かりますか?
; bit-index->number : natural -> natural
; return the number which in binary notation has a 1 in position n
; and 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
; is bit n set in the number x?
(define (is-bit-set? n x)
; the bitwise-and is zero unless bit n is set in the number x
(not (zero? (bitwise-and (bit-index->number n) x))))
(define (set-bit! n x b)
(cond
[(= b 1) ; we need to set bit n in x to 1
(cond
[(is-bit-set? n x) x] ; it was already set
[else (+ x (bit-index->number n))])] ; add 2^n
[(= b 0)
; <what goes here?>
]))
ここで行ったことを説明してください。 (ちょうどその場合、変更するビットのインデックスは右から左に1からnまでカウントする必要があります) – BVtp
答えが良いとすれば、もう少し詳細。 –