Binary 在Scheme(Racket)中更改二进制数中的特定索引位

Binary 在Scheme(Racket)中更改二进制数中的特定索引位,binary,scheme,lisp,racket,Binary,Scheme,Lisp,Racket,我需要在Scheme中实现改变二进制数中特定位的可能性 输入为:1.二进制数,2.要更改的位的索引,3.在该索引中设置的值 如何实现这一点?以下是解决方案的开始。你能看到在剩下的情况下需要做什么吗 (define (set-bit value index n) (let ([mask (arithmetic-shift 1 index)]) (cond [(= value 0) (bitwise-and (bitwise-not mask) n)] [(= val

我需要在Scheme中实现改变二进制数中特定位的可能性

输入为: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进行计数……只要答案可能是好的,就有必要提供更多的细节。